jQuery Set Select Index

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

I have an select box:


                        
    
提交评论

  • 2020-11-27 09:54

    I faced same problem. First you need go through the events (i.e which event is happening first).

    For example:

    The First event is generating select box with options.

    The Second event is selecting default option using any function such as val() etc.

    You should ensure that the Second event should happen after the First event.

    To achieve this take two functions lets say generateSelectbox() (for genrating select box) and selectDefaultOption()

    You need to ensure that selectDefaultOption() should be called only after the execution of generateSelectbox()

    0 讨论(0)
  • 2020-11-27 09:55

    Select the item based on the value in the select list (especially if the option values have a space or weird character in it) by simply doing this:

    $("#SelectList option").each(function () {
        if ($(this).val() == "1:00 PM")
            $(this).attr('selected', 'selected');
    });
    

    Also, if you have a dropdown (as opposed to a multi-select) you may want to do a break; so you don't get the first-value-found to be overwritten.

    0 讨论(0)
  • 2020-11-27 09:56

    Try this instead:

    $("#selectBox").val(3);
    
    0 讨论(0)
  • 2020-11-27 09:58

    The pure javascript selectedIndex attribute is the right way to go because,it's pure javascript and works cross-browser:

    $('#selectBox')[0].selectedIndex=4;
    

    Here is a jsfiddle demo with two dropdowns using one to set the other:

    <select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
      <option>0</option>
      <option>1</option>
      <option>2</option>
    </select>
    
    <select id="selectBox">
      <option value="0">Number 0</option>
      <option value="1">Number 1</option>
      <option value="2">Number 2</option>
    </select>
    

    You can also call this before changing the selectedIndex if what you want is the "selected" attribute on the option tag (here is the fiddle):

    $('#selectBox option').removeAttr('selected')
       .eq(this.selectedIndex).attr('selected','selected');
    
    0 讨论(0)
  • 2020-11-27 09:59

    Hope this could help Too

    $('#selectBox option[value="3"]').attr('selected', true);
    
    0 讨论(0)
  • 提交回复
    热议问题