Reputation: 546
I have 2 forms on 1 page. I am trying to get the value of the name field from the first form using jQuery but jQuery is always getting the name value from the 2nd form. The code looks like this:
$('#registration-form').each(function(){
var $this = $(this);
$this.submit(function (event) {
var firstName = $(this).find('input[name="firstName"]').val();
console.log(firstName);
});
});
Why is this code not working? Your help is much appreciated!
Upvotes: 1
Views: 41
Reputation: 337600
Firstly you're selecting by id
attribute, so you cannot have more than one element with the same id
. This is why only one is found. The each()
is also redundant in this case.
If you want to group elements use a class
instead, although note that the each()
is still redundant as jQuery will loop over each selected element internally so you can just attach the submit
event handler directly, like this:
$('.reg-form').submit(function (e) {
var firstName = $(this).find('input[name="firstName"]').val();
console.log(firstName);
});
Upvotes: 1