I have the following jQuery method that iterates over a selectlist containing a number of options. I want to hihlight the first line that has a match for some text typed by the user into a textbox named MMDCriteria. Currently the code is selecting and highlighting each item in turn until it gets to the end of the list.
$("#MMDCriteria").bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
var criteria = $(this).val().toUpperCase();
alert("");
$('select#MMD > option').each(function() {
var optionValue = $(this).text().toUpperCase();
alert(optionValue.substring(0, optionValue.indexOf(criteria)));
if(optionValue.substring(0, optionValue.indexOf(criteria)) > -1) {
$(this).attr('selected', 'selected');
}
});
}
});
I have only just started using jQuery so excuse the verboseness.
It’s highlighting multiple options because the
eachfunction is running for each option in the select list. You have to break out of the loop as soon as the first matching option is found by returningfalse. Modify the code roughly as:Alternatively, use a simple for-loop that keeps the logic clear.
Also, jQuery already normalizes the event object so you don’t have to check for
keyCodeorwhich. The property will always be namedwhich.