Reputation: 47
I have a simple form and a reset button. I'd like to add a class to the reset button if form fields are default.
I put together this code, which works great, only problem is it's set to on change and reset button switches class upon click. So if someone changes a input field back to default without hitting the reset button, the reset button stays how it is.
Is there a way to detect if form fields are default? Then add class based on that? Here's my code;
Button
<button type="reset" class="myreset">Reset</button>
Script
$("#myform input").change(function() {
$(".myreset").addClass("blue");
});
$(".myreset").click(function() {
$(this).removeClass("blue");
});
Upvotes: 2
Views: 65
Reputation: 193291
I would make it a little more abstract, but more flexible. Consider this code:
var $form = $("#myform"),
$reset = $form.find(".myreset");
// Store initiale state
$form.data('reset', $form.serialize());
// Listen change and keyup events
$form.find('input, textarea').on('change keyup', function() {
var clear = $form.serialize() == $form.data('reset');
$reset.trigger(clear ? 'click' : 'dirty');
});
// Reset button events
$reset.on({
dirty: function() {
$(this).addClass('blue');
},
click: function() {
$(this).removeClass('blue');
}
});
The key idea is to on each input change (keyup or change event) compare previously stored form serialized state with the new one. This way you can always say if the form in its pristine state or not.
I also added events to reset button. It makes code even more unobtrusive: you might not only want to change class name but do something else, and $form.find('input, textarea')
listeners doesn't have to know what exactly happens to reset button.
Upvotes: 1