Reputation: 59
I have tabs with forms in each of them and on click of reset button, it resets form fields of that form only.
//Reset respective forms
$('#thresholds .reset').on('click', function() {
$('#thresholds').trigger("reset");
});
$('#attributes .reset').on('click', function() {
$('#attributes').trigger("reset");
});
$('#rules .reset').on('click', function() {
$('#rules').trigger("reset");
});
$('#events .reset').on('click', function() {
$('#events').trigger("reset");
});
#thresholds, #attributes, #rules, #events are the form IDs.
How can I optimise this for code repetition?
Upvotes: 0
Views: 32
Reputation: 2993
You can identify all reset
click with .reset
class and then select closest from
of this button and apply reset trigger
.
Please find below mentioned code. This will help you.
$('.reset').on('click',function(e){
e.preventDefault();
$(this).closest('form').trigger('reset');
});
Check working example below.
$('.reset').on('click',function(e){
e.preventDefault();
$(this).closest('form').trigger('reset');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="thresholds">
<input type="text" />
<input type="button" class='reset' value="Reset" />
</form>
<form id="attributes">
<input type="text" />
<input type="button" class='reset' value="Reset" />
</form>
<form id="rules">
<input type="text" />
<input type="button" class='reset' value="Reset" />
</form>
<form id="events">
<input type="text" />
<input type="button" class='reset' value="Reset" />
</form>
Let me know if it not works.
Upvotes: 2
Reputation: 8249
You can merge them like this:
$('#thresholds .reset, #attributes .reset, #rules .reset, #events .reset').on('click', function() {
$(this).parents('form:first').trigger("reset");
});
Upvotes: 0