Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

JSON record not found, manually typed rating disappears. How to fix that? JavaScript

  • SOLVED

I have a js problem. My web app (https://verlager.com/cccr/) automatically fills in the input rating of an existing (JSON members) record. But if I manually enter a rating of a player whose name is not in the JSON member list, that value is erased on a tab press or mouse click. I want to fix that and retain that rating value. The column header sorts should NOT destroy values in input fields.

Chessplayers from other cities are frequently walking into our club and our meager local member json file can't find their rating because the record doesn't exist. We look up their ratings in a reference book, but we need to enter that rating info in the program to produce pairings. Without it being erased.

I don't even think onblur="getClass();" in the <input> is necessary. The code below I think updates all 64 rating input fields at once. May be better to process them individually.

members =
[{"ID":17118888,"Name":"Rodriguez, Roberto F","Exp":"2020-09-30","Rate":0},
{"ID":16720664,"Name":"Adeyemon, Murie","Exp":"2019-05-31","Rate":0},
{"ID":12901834,"Name":"Agok, Peter Panther","Exp":"2019-03-31","Rate":1754}]

<input tabindex = "-1" type = "text" onblur="getClass();" name = "rating" class="RANK number" maxlength = "4" size = "4" id = "Y3" />

<script> // Lookup Rating

for (let i = 0; i <= 64; i++) {
$("#P" + i).on("blur", function(){

$("#Y" +i).val(getClass(this));
});
}

function getClass(ele) {
var i = null;
for (i = 0; members.length > i; i++) {

if (members[i].Name == ele.value) {return members[i].Rate;}
}
return;
}

</script>

Answers (1)

2019-09-19

Rainner Lins answers:


$("#Y" +i).val(getClass(this));


That line will always set the value of the input, even if it's empty, which is what's happening. You need to check if the value is there before adding it. Try wrapping that in an if statement.


$("#P" + i).on("blur", function(){
const rating = getClass(this);
if (rating) {
$("#Y" +i).val(rating);
}
});


User180435 comments:

This doesn't work. Try entering "MacKenzie" (a JSON lookup value exists) in the left input field and press tab. NO rating shows up!


User180435 comments:

The code at verlager.com/cccr is updated per your instructions