开发者

Iterating a selectlist to highlight an item, highlights each item in turn

开发者 https://www.devze.com 2023-01-09 03:29 出处:网络
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 name

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.in开发者_如何学PythondexOf(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 each function 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 returning false . Modify the code roughly as:

..
var notFound = true; // 1) initialize a shared variable

$('select#MMD > option').each(function() {
    ..
    if(found a match) {
        ..
        notFound = false; // 2) update it's value to force exit from loop
    }
    return notFound; // 3) keep iterating until notFound is true
});
..

Alternatively, use a simple for-loop that keeps the logic clear.

...
var options = $('#MMD > option');
for(var i = 0; i < options; i++) {
    if found a match {
        add "selected" attribute
        return; // exists the `keypress` function immediately
    }   
}
..

Also, jQuery already normalizes the event object so you don't have to check for keyCode or which. The property will always be named which.

0

精彩评论

暂无评论...
验证码 换一张
取 消