html - Else block of javascript program always executes even If block is true -
else block keeps executing if true. if remove else block program works fine. want check if user not in record prints not found.
var students = [ { name: "linda", track: "ios", points:' 50' }, { name: "brian", track: "android", points: '80' }, { name: 'trish', track: 'rails development', points: '350' } ]; var search = " "; var student; var message = " "; function print ( msg ) { var output = document.getelementbyid("output"); output.innerhtml = msg; } function studentreport( student ) { var report = "<h2> student name: " + " " + student.name + "</h2>"; report += "<p> student track: " + " " + student.track+ "</p>"; report += "<p> student points: "+ " " + student.points+ "</p>"; return report; } var button = document.getelementbyid("search"); /*search = prompt("enter name search database or type quit exit");*/ button.onclick = function( ) { search = document.getelementbyid("txtfield").value; for( var = 0; < students.length; i++ ) { student = students[i]; if( student.name.tolowercase() === search.tolowercase() ) { message = studentreport(student); print(message); } else { message = "<h2> student not found </h2>"; print( message); } } }
<div class="container"> <form action="#"> <input type="text" name="search" id="txtfield"><!-- --><a href="#" id="search"> search </a> </form> <div id="output"> </div> </div>
by removing else part program search names , displays student records. else part should check if student not present in array prints not found.
add break;
if
statement, loop stops evaluating. otherwise, last result update html.
Comments
Post a Comment