samedi 21 octobre 2017

Simple if statement inside jquery $.each function not returning right value

I'm unable to get a basic if statement inside a jquery $.each loop working. I have a json object that I loop through, and if the value entered in a text box is found in the json object, I return a flag I set as false. But for some reason, the if statement is not executing. Here is the code:

var authorlist = [{"AUTHOR":"DONNA EDWARDS","COUNTRY":"USA","REGION":"MIDWEST"},{"AUTHOR":"EMERALD JONES","COUNTRY":"UK","REGION":"EU"},{"AUTHOR":"SHAKESPEARE","COUNTRY":"UK","REGION":"EU"}];

function checkName(){
  var nameIsValid = true;
  var nametocheck = $("#name").val();

  $.each(authorlist, function(index, val){
    //console.log(val.AUTHOR);
    if(nametocheck == val.AUTHOR){
    //console.log(val.AUTHOR);
    nameIsValid = false;
    return false;
   }
 });
 return nameIsValid;
}

$("#btnCheck").on("click", function(){
console.log("The name entered is valid: " + checkName());
});

Here is the jsfiddle: http://ift.tt/2yxpFJP

Aucun commentaire:

Enregistrer un commentaire