Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 817
Becky Avatar asked Aug 12 '10 14:08

Becky


3 Answers

you can even use 'this' context

var fname = $('input.fname', this).val();
like image 56
IcanDivideBy0 Avatar answered Oct 20 '22 23:10

IcanDivideBy0


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?

like image 35
CaffGeek Avatar answered Oct 21 '22 00:10

CaffGeek


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();

});
like image 2
UpHelix Avatar answered Oct 20 '22 22:10

UpHelix