How to set the first option on a select box using jQuery?

前端 未结 17 827
终归单人心
终归单人心 2020-11-28 03:18

I have two HTML select boxes. I need to reset one select box when I make a selection in another.


                        
    
提交评论

  • 2020-11-28 03:45

    I created a new option in the select tag that has a value of empty string ("") and used:

    $("form.query").find('select#topic').val("");
    
    0 讨论(0)
  • 2020-11-28 03:49

    Here is the best solution im using. This will apply for over 1 slectbox

    $("select").change(function(){
        var thisval = $(this).val();
        $("select").prop('selectedIndex',0);
        $(this).val(thisval);
    })

    0 讨论(0)
  • 2020-11-28 03:53

    Something like this should do the trick: https://jsfiddle.net/TmJCE/898/

    $('#name2').change(function(){
        $('#name').prop('selectedIndex',0);
    });
    
    
    $('#name').change(function(){
        $('#name2').prop('selectedIndex',0);
    });
    
    0 讨论(0)
  • 2020-11-28 03:55

    Here's how to handle it with a random option element defined as the default value (in this case Text 2 is the default):

    <select id="name2" >
       <option value="">select all</option>
       <option value="1">Text 1</option>
       <option value="2" selected="selected">Text 2</option>
       <option value="3">Text 3</option>
    </select>
    <script>
        $('#name2 option[selected]').prop('selected', true);
    </script>
    
    0 讨论(0)
  • 2020-11-28 03:57

    As pointed out by @PierredeLESPINAY in the comments, my original solution was incorrect - it would reset the dropdown to the topmost option, but only because the undefined return value resolved to index 0.

    Here's a correct solution, which takes the selected property into account:

    $('#name').change(function(){
        $('#name2').val(function () {
            return $(this).find('option').filter(function () {
                return $(this).prop('defaultSelected');
            }).val();
        });
    });
    

    DEMO: http://jsfiddle.net/weg82/257/


    Original answer - INCORRECT

    In jQuery 1.6+ you need to use the .prop method to get the default selection:

    // Resets the name2 dropdown to its default value
    $('#name2').val( $('#name2').prop('defaultSelected') );
    

    To make it reset dynamically when the first dropdown changes, use the .change event:

    $('#name').change(function(){
      $('#name2').val( $('#name2').prop('defaultSelected') );
    });
    
    0 讨论(0)
  • 提交回复
    热议问题