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

前端 未结 17 828
终归单人心
终归单人心 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 04:06

    Here is how I got it to work if you just want to get it back to your first option e.g. "Choose an option" "Select_id_wrap" is obviously the div around the select, but I just want to make that clear just in case it has any bearing on how this works. Mine resets to a click function but I'm sure it will work inside of an on change as well...

    $("#select_id_wrap").find("select option").prop("selected", false);
    
    0 讨论(0)
  • 2020-11-28 04:06

    You can try this:

    $( 'select' ).each( function () {
        if ( $( this ).children().length > 0 ) {
            $( $( this ).children()[0] ).attr( 'selected', 'selected' );
            $( this ).change();
        }
    } );
    
    0 讨论(0)
  • 2020-11-28 04:07

    I had a problem using the defaultSelected property in the answer by @Jens Roland in jQuery v1.9.1. A more generic way (with many dependent selects) would be to put a data-default attribute in your dependent selects and then iterate through them when reseting.

    <select id="name0" >
        <option value="">reset</option>
        <option value="1">Text 1</option>
        <option value="2">Text 2</option>
        <option value="3">Text 3</option>
    </select>
    
    <select id="name1" class="name" data-default="1">
        <option value="">select all</option>
        <option value="1" selected="true">Text 1</option>
        <option value="2">Text 2</option>
        <option value="3">Text 3</option>
    </select>
    
    <select id="name2" class="name" data-default="2">
        <option value="">select all</option>
        <option value="1">Text 1</option>
        <option value="2" selected="true">Text 2</option>
        <option value="3">Text 3</option>
    </select>
    

    And the javascript...

    $('#name0').change(function(){
        if($('#name0').val() == '') {
            $('select.name').each(function(index){
              $(this).val($(this).data('default'))  
            })
        } else {
          $('select.name').val($('#name0').val() );
        }
    });
    

    See http://jsfiddle.net/8hvqN/ for a working version of the above.

    0 讨论(0)
  • 2020-11-28 04:08

    This can also be used

    $('#name2').change(function(){
        $('#name').val('');//You can set the first value of first one if that is not empty
    });
    
    
    $('#name').change(function(){
        $('#name2').val('');
    });
    
    0 讨论(0)
  • 提交回复
    热议问题