Use jquery variable and loop in Ajax post data

Nori

I don't really know how to use the Ajax post data function, but i'm using some free simple file and trying to tweak it a little bit.

The simple code part that i want to change is that:

post_data = {
'clcon_user_name'       : $('input[name=name]', clientConParent).val(),
'clcon_user_lastname'   : $('input[name=lastname]', clientConParent).val(),
'clcon_user_email'  : $('input[name=email]', clientConParent).val(),
'clcon_phone_number'    : $('input[name=phone]', clientConParent).val(),
'clcon_msg'         : $('textarea[name=message]', clientConParent).val(),
'pro_mailto'    : $('input[name=promailto]', clientConParent).val()
};

I want to make it dynamic so it will loop through the fields on my form and grab them all in this format: 'npf_{the name atrr of the field}' : $('input[name={the name atrr of the field}]', theForm).val(), for the post_data (for the Ajax $.post(... function).

I tried:

post_data = {
$("input, textarea, select", theForm).each(function(){
'\'npf_$'+$(this).attr('name')'\'' : $('input[name='++$(this).attr('name')+']', theForm).val(),
});
};

Didn't work, also tried:

post_data = {
$("input, textarea, select", theForm).each(function(){
var theName = $(this).attr('name');
'npf+theName' : $('input[name='+theName+']', theForm).val(),
});
};

Didn't work, also tried:

post_data = {
$("input, textarea, select", theForm).each(function(){
var theName = $(this).attr('name');
'npf+theName' : $('input[name='+theName+']', theForm).val(),
});
};

I know i must be doing a couple of things here wrong... i can use some "For Dummies" explanation sense i'm a beginner.

Brett

Create an empty object and then loop through your form to set the properties on that object.

post_data = { };

$("input, textarea, select", theForm).each(function(){
    var theName = $(this).attr('name');
    post_data['npf_' + theName] = $(this).val();
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related