Sam Skirrow Sam Skirrow - 2 months ago 6
jQuery Question

jQuery how to combine this and a variable

I have a form where the ID changes depending on the page.

I am trying to get the value of the input name

email
but am using
$(this)
to make sure I don't conflict with any other forms that may be on the same page.

Here is my jQuery code:

jQuery(document).ready(function($) {
$('#layers-widget-form_builder-27 .builderForm').each(function() {
$(this).on("submit", function(event) {
event.preventDefault();
var formData = $(this).serialize();
var emailId ='sam.skirrow@gmail.com';
var emailSubject ='New website form submission';
var mcListID ='9069741672';
var mcAPIkey ='d87ebb1e2bf13d4624009f2f5ea9a9aa-us12';
var mcEmail = $(this + 'input[name="email"]').val();
var mcLname ='last_name';
var mcFname ='first_name';
var mcForm = $(this);

...

});
});
});


To create a var for email I am using

var mcEmail = $(this + 'input[name="email"]').val();


but this is throwing up syntax errors - what is the correct way of combining $this with a selector?

Answer

You can use the find method to find the descendants within an element.

var mcEmail = $(this).find('input[name="email"]').val();