简体   繁体   中英

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.

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());
});

To get the value of each checked radio button on a page, simply loop through them, filtering only the checked radio inputs and run whatever code you want on each occurrence.

var formData = new FormData();

$('input[type=radio]').filter(':checked').each(function () {
    var inputField = $(this);
    formData.append(inputField.attr('name'), inputField.val());
});

You need to serialize the list of selected radio buttons before you send via Ajax.

var radioChecked = $(":radio").serialize();
$.ajax(
        {
             url: _action_url,
             data: radioChecked,
             success: function(result){
                 // What do we do when success
             }
        }
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM