Reputation: 26117
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
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:
<input id="resetbutton" type="reset" style="visibility:hidden;" name="reset" value="reset" />
<a href="#" onclick="$('#resetbutton').click();">Reset</a>
Upvotes: 0
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
<select>
elementsexample:
<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
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
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