Becky
Becky

Reputation: 348

jQuery get THIS form input

I am trying to get the values of multiple form inputs, but the problem is I have several identical forms on the same page and only want to get the inputs from the form that was submitted, so I am using the 'this' keyword. This is my code:

$('form.contact_form').submit(function(e) {
    var fname = $(this).children('input.fname').val();
    var email = $(this).children('input.email').val();
    var comment = $(this).children('input.comment').val();

However, when I try to log the variables to test they're returning the wrong values, it says they are all undefined. What would be the right way to do this?

Thanks for any help :D

Upvotes: 7

Views: 25063

Answers (4)

user45678
user45678

Reputation: 341

For later versions of jQuery. I'm using >3.0

var fname = $(this,''input.fname'').val();

I'm adding this because none of the other answers worked for me until I solved it myself. Hope it can also help you. Cheers

Upvotes: 0

Mechlar
Mechlar

Reputation: 4974

Use .find() as Chad suggested.

$('form.contact_form').submit(function(e) {
    var $this = $(this);
    var fname = $this.find('input.fname').val();
    var email = $this.find('input.email').val();
    var comment = $this.find('input.comment').val();

});

Upvotes: 2

IcanDivideBy0
IcanDivideBy0

Reputation: 1675

you can even use 'this' context

var fname = $('input.fname', this).val();

Upvotes: 9

CaffGeek
CaffGeek

Reputation: 22054

Need to see the HTML.

But, are they direct children of the form?
Or should you be using .find, instead of .children because they are nested lower?

Upvotes: 7

Related Questions