简体   繁体   中英

Jquery, select dropdown option on Event

I have a Jquery with event keyup. It select dropdownList(CityId) option, which text is liked/samme as a user write in inputbox(finpost).

The problem is that only work once.. I cant see whats wrong ?! Help

$(document).ready(function () {

    $('#finpost').keyup(function ()
    {
        $("#CityId > option").each(function ()
        {
            var t = this.text.toUpperCase();
            if (t.indexOf($('#finpost').val().toUpperCase()) != -1)
            {
                $(this).attr("selected", 'true');
                return false;
            }                
        });

    });
});

This work only once because your list can have only one selected option per time, but in your script logic you are setting attribute selected to true every time you find a matching without re-initializing others options

I think you should be good to go if you try this

$(document).ready(function () {

    $('#finpost').keyup(function ()
    {
        var matchingFound = false;
        $("#CityId > option").each(function ()
        {
            var t = this.text.toUpperCase();
            if (t.indexOf($('#finpost').val().toUpperCase()) != -1 && !matchingFound)
            {
                $(this).attr("selected", 'true');
                matchingFound = true;
            }
            else {
                $(this).attr("selected", "false");
            }                
        });

    });
});

Now its working. The problem wass this linie: $(this).attr('selected', true);..

I changed it to $(this).prop('selected', true); and its work

$(document).ready(function () {

    $('#finpost').keyup(function () {

        $("#CityId > option").each(function () {
            var t = this.text.toUpperCase();

            if (t.indexOf($('#finpost').val().toUpperCase()) != -1) {

                $(this).prop('selected', true);
                return false;
            }

        });

    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM