views:

1084

answers:

3

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

A: 

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

David
A: 

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')); 
});
Lance McNearney
+1  A: 

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>
Gaby