Get all input in div for ajax request
I am trying to get all input textboxes, radio groups, checkboxes etc. I am having trouble getting the selected radio and checkboxs values, I cant figure it out.
I can get the text boxes but can't seem to get the "selected" in the right place. At the moment it just gets the first value for radio/checkboxes not the selected value.
$('#form_1 input').each(function(key)
formData += '&'+$('#'+this.id).attr('name')+'='+$('#'+this.id).val();
});
Thanks
EDITED
$('#form_1 input').each(function(key, value) {
if ((this.type === "radio" || this.type === "checkbox") && this.checked === true) {
val = this.value;
} else {
val = this.value;
}
alert($('#'+this.id).attr('name') + ' = ' + val);
formData += '&'+$('#'+this.id).attr('name')+'='+val;
});
Ok now I get every value for ra开发者_JAVA技巧dios etc so I am a step closer. Just need to get the values of selected radios now.
Thanks
Just use the serialize()
[docs] method.
It will take care of getting the values of the selected elements for you.
var formData = $('#form_1').serialize();
From the docs:
The .serialize() method can act on a jQuery object that has selected individual form elements, such as , , and . However, it is typically easier to select the tag itself for serialization:
$('form').submit(function() { alert($(this).serialize()); return false; });
This produces a standard-looking query string:
a=1&b=2&c=3&d=4&e=5
var val;
if (this.type === "radio" || this.type === "checkbox") {
val = this.checked;
} else {
val = this.value;
}
For radios and check boxes you care about the checked attribute.
Update
You wrote
(this.type === "radio" || (this.type === "checkbox" && this.checked === true))
You meant
((this.type === "radio" || this.type === "checkbox") && this.checked === true)
You need those brackets in the right place.
Further edit
The logic was a bit broken.
Basically what you want.
if ((this.type === "radio" || this.type === "checkbox") && this.checked === false) {
return;
}
This means if its a non-checked radio/checkbox you do nothing.
This doesn't answer your question directly but it looks like you're trying achieve something that's already available - you might want to check out serialize()
- use it as var formData = $('#form_1').serialize()
精彩评论