jQuery Set Select Index

后端 未结 24 1562
无人共我
无人共我 2020-11-27 09:52

I have an select box:


                        
    
提交评论

  • 2020-11-27 10:00

    What's important to understand is that val() for a select element returns the value of the selected option, but not the number of element as does selectedIndex in javascript.

    To select the option with value="7" you can simply use:

    $('#selectBox').val(7); //this will select the option with value 7.
    

    To deselect the option use an empty array:

    $('#selectBox').val([]); //this is the best way to deselect the options
    

    And of course you can select multiple options*:

    $('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7
    

    *However to select multiple options, your <select> element must have a MULTIPLE attribute, otherwise it won't work.

    0 讨论(0)
  • 2020-11-27 10:02

    I need a solution that has no hard coded values in the js file; using selectedIndex. Most of the given solutions failed one browser. This appears to work in FF10 and IE8 (can someone else test in other versions)

    $("#selectBox").get(0).selectedIndex = 1; 
    
    0 讨论(0)
  • 2020-11-27 10:04

    You can also init multiple values if your selectbox is a multipl:

    $('#selectBox').val(['A', 'B', 'C']);
    
    0 讨论(0)
  • 2020-11-27 10:05

    In 1.4.4 you get an error: $("#selectBox option")[3].attr is not a function

    This works: $('#name option:eq(idx)').attr('selected', true);

    Where #name is select id and idx is the option value you want selected.

    0 讨论(0)
  • 2020-11-27 10:08

    NB:

    $('#selectBox option')[3].attr('selected', 'selected') 
    

    is incorrect, the array deference gets you the dom object, not a jquery object, so it will fail with a TypeError, for instance in FF with: "$('#selectBox option')[3].attr() not a function."

    0 讨论(0)
  • 提交回复
    热议问题