How to reset multiple select fields in a form with jquery?

How can I reset multiple select blocks in a form with jquery?

  • there are several blocks of choice
  • they are dynamically generated and we don’t know what they will be
  • some of the option tags will be marked as highlighted
  • fiddle: http://jsfiddle.net/Qnq82/

I have it so far, it resets everything except the selected ones.

$('button#reset').click(function(){
    $form = $('button#reset').closest('form');
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    $form.find('select').selectedIndex = 0;
  });

Added inscription:

<form id="form" name="form" method="post" class="form" role="form" action="inventory-search" enctype="multipart/form-data">


    <div class="form-group">
        <label for="grade">Grade</label>
        <select name="grade" class="form-control input-sm" onchange="this.form.submit();">
            <option value="">Any</option>
            <option value="opt1">opt1</option>
            <option value="opt2" selected="selected">opt2</option>

        </select>
    </div>


    <!-- there are 6 more select controls -->


    <div class="form-group">
        <label>&nbsp;</label>
        <button type="submit" name="search" id="search" value="search" class="btn button-sm btn-primary">Search</button>
    </div>

    <div class="form-group">
        <label>&nbsp;</label>
        <button type="reset" name="reset" id="reset" value="reset" class="btn button-sm btn-primary">Reset</button>
    </div>

</form>
+4
source share
4 answers

This will work: -

$form.find('select').prop('selectedIndex',0);
+4
source

Deselect all html in the form with this succesfuly code:

$("#form1").find('select').prop('selectedIndex', -1);
+2
source

I tried a lot and searched a lot in StackOverFlow, but did not get any solution to reset multiselect.Then I found this link . This solved my problem. Here is a sample code.

$("#yourcontrolid").multiselect('clearSelection');
+1
source

Change the last line as follows:

$form.find('select')[0].selectedIndex = 0;

selectedIndexis a property HTMLElement, not a jQuery object.

If you know the meaning, you can do $form.find('select').val('value');

0
source

Source: https://habr.com/ru/post/1548573/


All Articles