Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery get radio button selection

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.

like image 778
Ron Butcher Avatar asked Nov 01 '22 10:11

Ron Butcher


2 Answers

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]);
like image 74
Arun P Johny Avatar answered Nov 09 '22 12:11

Arun P Johny


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());
});
like image 30
Agop Avatar answered Nov 09 '22 12:11

Agop