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

前端 未结 17 829
终归单人心
终归单人心 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:58

    This helps me a lot.

    $(yourSelector).find('select option:eq(0)').prop('selected', true);
    
    0 讨论(0)
  • 2020-11-28 03:59

    If you just want to reset the select element to it's first position, the simplest way may be:

    $('#name2').val('');
    

    To reset all select elements in the document:

    $('select').val('')
    

    EDIT: To clarify as per a comment below, this resets the select element to its first blank entry and only if a blank entry exists in the list.

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

    Use this code to reset all selection fields to the default option, where the attribute selected is defined.

    <select id="name1" >
        <option value="1">Text 1</option>
        <option value="2" selected="selected" >Default Text 2</option>
        <option value="3">Text 3</option>
    </select>
    <select id="name2" >
        <option value="1">Text 1</option>
        <option value="2">Text 2</option>
        <option value="3" selected="selected" >Default Text 3</option>
    </select>
    <script>
        $('select').each( function() {
            $(this).val( $(this).find("option[selected]").val() );
        });
    </script>
    
    0 讨论(0)
  • 2020-11-28 04:02

    Setting option 1 in the select element can be done by this segment. To visually show it, you have tp add .trigger('change') at the end.

    $('#name').removeAttr('selected').find('option:first').attr('selected', 'selected').trigger("change");
    
    0 讨论(0)
  • 2020-11-28 04:03

    This is the most flexible/reusable way to reset all select boxes in your form.

          var $form = $('form') // Replace with your form selector
          $('select', $form).each(function() {
            $(this).val($(this).prop('defaultSelected'));
          });
    
    0 讨论(0)
  • 提交回复
    热议问题