Jake
Jake

Reputation: 26117

JQuery - Form Reset - Exclude "Select" box

All,

I can reset all my form elements using the following JQuery Syntax:

('#myform')[0].reset();

How can I modify this to exclude the reset of "select box" values?

Thanks

Upvotes: 8

Views: 26760

Answers (4)

Keith Wagner
Keith Wagner

Reputation: 41

For whatever reason, David's right-on answer error'd my Google Chrome js. It's saying:

Uncaught TypeError: Property 'reset' of object # is not a function

...so I decided to try a slightly different solution:

  • Give native browser reset buttons attributes "hidden" and set "id":

<input id="resetbutton" type="reset" style="visibility:hidden;" name="reset" value="reset" />

  • Initiate JQuery "click" event on reset button from clicking link:

<a href="#" onclick="$('#resetbutton').click();">Reset</a>

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

To everyone..

the reset function does not set everything to '' (empty string)

it reset to their initial values .. (stored in the value attribute, or selected option etc..)

If you want to maintain the default reset features then you should

  1. get all the <select> elements
  2. get their currently selected values
  3. reset the form as you currently do
  4. re-set the selected

example:

<script type="text/javascript">
  $(document).ready(
  function(){
   $("#resetbutton").click(
    function(){
     var values = [];
     var selected = $("select").each(
      function(){
       values.push( $(this).val());
       });
     this.form.reset();
     for (i=0;i<selected.length;i++)
      $(selected[i]).val(values[i]);
    });
    }
  );
 </script>

Upvotes: 10

Lance McNearney
Lance McNearney

Reputation: 9490

You can do a fake reset by setting the values to an empty string and resetting the checkboxes using David's answer (or this more complete one). You could also try storing each select element's value before resetting the form and then restore the values after:

var myform = $('#myform');
var selects = $('select', myform);

// Store each current value
selects.each(function() {
    $(this).data('previous', $(this).val()); 
});

myform[0].reset();

// Restore the values
selects.each(function() {
    $(this).val($(this).data('previous')); 
});

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

That's not jQuery, it's native javascript. [0] brings out the actual DOM element, so it's the same as:

document.getElementById('myform').reset();

reset() is a built-in browser implementation that resets the entire form. If you need to reset individual form types, try something like:

$('#myform :text').val('');

You can see all form selectors here: http://docs.jquery.com/Selectors

Upvotes: 6

Related Questions