user1190132
user1190132

Reputation: 546

2 similar forms on the one page, $(this).find(); is getting value from the last form

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

Answers (1)

Rory McCrossan
Rory McCrossan

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

Related Questions