How do I programmatically set the value of a select box element using JavaScript?

后端 未结 17 1972
轮回少年
轮回少年 2020-11-22 06:33

I have the following HTML

17条回答
  •  感动是毒
    2020-11-22 06:39

    I compared the different methods:

    Comparison of the different ways on how to set a value of a select with JS or jQuery

    code:

    $(function() {
        var oldT = new Date().getTime();
         var element = document.getElementById('myId');
        element.value = 4;
        console.error(new Date().getTime() - oldT);
    
        oldT = new Date().getTime();
        $("#myId option").filter(function() {
            return $(this).attr('value') == 4;
        }).attr('selected', true);
        console.error(new Date().getTime() - oldT);
    
        oldT = new Date().getTime();
        $("#myId").val("4");
        console.error(new Date().getTime() - oldT);
    });
    

    Output on a select with ~4000 elements:

    • 1 ms
    • 58 ms
    • 612 ms

    With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options). We had roughly 2 s delay after a val()

    Note as well: I am setting value depending on the real value, not the text value.

提交回复
热议问题