samedi 29 avril 2017

else condition is always executed even if the if statement is true

I am trying forever to fix this code: i have a list and i am searching through the list to find students. Once i don't find a student, an error message should appear. At the moment i have a function who searches the student based on text match. I have an if statement inside the function. When the match is found show student and when not, hide all the students. I created a variable 'found' set to 'true' when the student is found. if this is false the message should be appended.

The problem is that both conditions are being executed it seems so if i put found as being false inside the second condition the error message will display every time.

At the moment i have another if which checks if found was false. the problem is it doesn't recognise that it is false...so confusing. Please see screenshot with the console where you can see that although the student is found, the second condition is executed each time... screenshot with the console - second condition is always executed

First condition doesn't execute unless it's true.

Please help as I am trying to investigate this forever and I asked lots of questions here around this issue but with no big results.

Thanks so much, Alina

//add search bar 
$( ".page-header" ).append('<div class="student-search"></div>');
$( ".student-search" ).append('<input id="input-search" placeholder="Search for students..."/><button id="search">Search</button>');

// append to the .page the container div for the error message
$('.page').append('<div class="error"></div>'); 
// append to the error div a p with the error message if student is not found

var found = true;


//myFunction
function myFunction() {  
    var input = document.getElementById("input-search");
    var filter = input.value.toUpperCase();
    for (var i = 0; i < li.length; i+=1) {  
        var h = li[i].getElementsByTagName("h3")[0];
        if (h.innerHTML.toUpperCase().indexOf(filter) != -1) {
            li[i].style.display = ""; 
            console.log('yey found it');
            found = true;
        } else {
            li[i].style.display = "none";   
            console.log('condtion 2');
        }      
      } 
      if (found===false) {
         $('.error').append('<p>"student not found!"</p>');  
      }
    $('.pagination').hide();
}

//myFunction end
$('#search').on('click', function(){
      myFunction();         
});

// when the input is empty return to page 1, empty the error div, show pagination, 

$('#input-search').on('keyup', function() {
 if($(this).val() === '') {
   go_to_page(0);
   $('.pagination').show();
  }
});

Aucun commentaire:

Enregistrer un commentaire