Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  • there are multiple select boxes
  • they are dynamically generated & we don't know what they will be
  • some of the boxes option tags will be marked as selected
  • fiddle: http://jsfiddle.net/Qnq82/

I have this so far, it resets everything but the selects.

$('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 some markup:

<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>
like image 459
Sean Kimball Avatar asked Jul 16 '14 02:07

Sean Kimball


People also ask

How to reset multiple select box in jQuery?

$('select[multiple]'). multiselect('reload') needs to reset the select options.

How do you reset values in a form?

reset() method restores a form element's default values. This method does the same thing as clicking the form's <input type="reset"> control. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method.

How we can reset form in jQuery?

JQuery doesn't have a reset() method, but native JavaScript does. So, we convert the jQuery element to a JavaScript object. JavaScript reset(): The reset() method resets the values of all elements in a form (same as clicking the Reset button).

What is Multiselect in jQuery?

jQuery multiselect is an easier and highly customizable substitute for the standard <select> with the multiple boxes. This is basically a plugin that is more user-friendly and easy to implement when it comes to multiple selections of the checkboxes.


1 Answers

This will work:-

$form.find('select').prop('selectedIndex',0);
like image 147
Mritunjay Avatar answered Oct 03 '22 14:10

Mritunjay