Reputation: 573
I have two identical forms with identical classes, I want to check if the fields are empty only for the submitted form - not for both forms.
Form HTML:
<form class="booking-form">
<input type="text" name="pickup-address" class="pickup-address" />
<button type="button" class="bookingbutton">
<span>Reserve Now</span>
</button>
</form>
JS:
$(".booking-form").on('click', '.bookingbutton', function () {
if ( $(".pickup-address").val() == '') {
alert('Please enter a pickup location');
return false;
}
});
The code I'm using works fine, but it checks both forms, I only want it to check for the form which the submit button was clicked on.
I know I could give each form a unqiue class but this isn't an option, so can I use $(this) to some how check only the form the submit button was clicked form?
Upvotes: 1
Views: 66
Reputation: 6442
Using jQuery it is possible to traverse up and down the DOM from a clicked element. In this case you could try using .closest
to traverse up to the nearest .booking-form
and then use that to search for your input
I would also suggest adding a required
attribute on the input
to have to browser provide some feedback about the element too.
$(".booking-form").on('click', '.bookingbutton', function () {
// find the closest form, because we have delegated the event, $(this) refers to the .bookingbutton element
var form = $(this).closest('.booking-form');
// check we found a form
if(form.length === 0) return;
// search within the found form for the .pickup-address
if ( form.find(".pickup-address").val() == '') {
alert('Please enter a pickup location');
return false;
}
});
As an alternative suggestion, you could toggle either the visibility, or disabled
state of the .bookingbutton
based upon the contents of any/all of your required fields
Upvotes: 2