Efficient way to write a jQuery if statement for multiple items
I have this form that is using da开发者_StackOverflow中文版ta-defaults and I need to be sure that they are cleared before submission. I have a jackhammer script that will do it, but I'm wondering if any of you would mind helping me finesse it.
The script below works and is perfectly fine if I want to write it for every input in the form (currently 8 with data defaults). I've tried selecting all of the inputs in the form with a few different approaches, but nothing seems to work. I imagine that there is a much smarter way to approach this than I am capable of, which is why I come here :)
$('#form_input_submit').click(function() {
if ($('#specific_input_id').val() == $('#specific_input_id').attr('data-default')) {
$('#specific_input_id').val('');
}
return true;
});
This will check all the input elements that have a default data element and clear those fields before submitting.
$('#tour_submit').click(function() {
$('input[data-default]').each(function(index) {
if ($(this).val() == $(this).attr('data-default')) {
$(this).val('');
}
});
});
You could get all the inputs in the form, and iterate over them. If some are radio or select inputs, we'll need to change it a little.
$('#form_input_submit').click(function() {
$(this).closest('form').find('input').each(function() {
if( this.value == $(this).attr('data-default') ) {
this.value = '';
}
});
});
On the click of your form_input_submit
button, it gets the .closest()
ancestor <form>
, and from there will .find()
all the <input>
elements.
Then it iterates over the collection using .each()
.
If $(this).attr('data-default')
represents the initial value of the input as it came from the server (or in any manner from its initial state), you could do this instead:
if( this.value == this.defaultValue ) {
this.value = '';
}
You can pass a function to .val()
, simplifying your code down to this for all inputs:
$('#form_id').submit(function() {
$(this).find('[data-default]').val(function(i, v) {
return $(this).data('default') == v ? "" : v;
});
});
Also, instead of attaching to the click
event of a submit button, this listens to the submit
event of the <form>
itself.
Try giving the all the input items a class, then do this
$('#form_input_submit').click(function() { $('.inputs').each(function() { if ($(this).val() == $(this).attr('data-default')) { $(this).val(''); } }); return true; });
精彩评论