1

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.

1

1 Answer 1

1

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();
});
Sign up to request clarification or add additional context in comments.

2 Comments

For some reason, if i use post_data['npf_' + theName] = $(this).val(); like you suggested it doesn't work, but if i use post_data['npf_' + theName] = $('input[name='+theName+']', theForm).val() it does. can you tell why?
Inside of the each loop this is bound to the current HTML element, if it works for getting the name of the element it should also be able to get the value. I suspect something else was wrong, but I can't tell what without seeing more of your code or the error you were getting. Here's an example showing it work: jsfiddle.net/jk8y0916/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.