jquery selection if option.value equal something, mark a selected

前端 未结 6 765
说谎
说谎 2021-02-12 19:45

I have some question about jquery selection. In my case, how to match if the option.value equal something, mark a selected for it. Online code here

6条回答
  •  一向
    一向 (楼主)
    2021-02-12 20:10

    You made a typo

    Instead of (this).val() you should use $(this).val() in your if statement. this refers to a HTMLObject, $(this) would refer to a jQuery object. Because the .val() method is part of the jQuery framework, you can't use it on HTMLObjects. But I'm sure you knew that because it looks very much like a small typo.

    This should work:

    $(document).ready(function(){
        var num = 3;
        $("div#selection select.select option").each(function(){
            if($(this).val()==num){ // EDITED THIS LINE
                $(this).attr("selected","selected");    
            }
        });
    });
    

    Edit

    You could optimize your loop by adding a return false; (break; for vanilla loops) when you have found your element so it doesn't keep looping elements while we're already "done".

    However, you should look at Nicola Peluchetti's answer for a more efficient and cleaner code.

提交回复
热议问题