I am trying to use JQuery and Ajax to submit a group of forms. The forms do not always have the same number of inputs or the same names to elements.
The code works fine for what I have with the exception of getting the values of which radio button is checked. It always returns the value of the last radio button.
Here is how I am getting the form data:
var values = {};
var formdata = new FormData();
$('form :input').each(function()
{
formdata.append(this.name, $(this).val());
});
I have also tried:
$('form.ajax :input, form.ajax input[type=radio]:checked').each(function()
What is the proper way to get the values of the checked radio button? I am hoping not to have to write a separate function for each form that I submit.
First you can select all input elements other than checkbox and radio and then append the values of selected checkbox and radio elements
var values = {};
var formdata = new FormData();
$('form').find(':input:not(:checkbox, :radio)').each(function () {
formdata.append(this.name, $(this).val());
});
$('form').find(':checkbox:checked, :radio:checked').each(function () {
formdata.append(this.name, $(this).val());
});
Why don't you try the below instead of creating the formdata manually
var formdata = new FormData($('form')[0]);
Your code is iterating through all of the inputs (radio buttons included) and adding their name-value pairs into the form data. The problem is that if you have multiple radio buttons, you'll only see the last name-value pair, because all of the radio buttons have the same name.
In order to handle the radio buttons correctly, you need to check if this.checked == true
, meaning this particular radio button is the checked one:
$('form :input').each(function()
{
if (this.type == 'radio' && !this.checked)
{
// this is a radio button, but it's not checked, so skip it
return;
}
formdata.append(this.name, $(this).val());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With