JQuery gets switch selection

I am trying to use jQuery and Ajax to submit a group of forms. Forms do not always have the same number of inputs or the same names for elements.

The code works fine for what I have, except that the values ​​that the switch is set to. It always returns the value of the last switch.

This is how I get the form data:

var values = {};
var formdata = new FormData();
$('form :input').each(function()
{
    formdata.append(this.name, $(this).val());
});

I also tried:

$('form.ajax :input, form.ajax input[type=radio]:checked').each(function()

What is the correct way to get the values ​​of a checked switch? I hope you don’t have to write a separate function for each form that I submit.

+4
source share
4 answers

, ,

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

, formdata​​p >

var formdata = new FormData($('form')[0]);
+2

( ) - . , , , .

, , this.checked == true, , :

$('form :input').each(function()
{
    if (this.type == 'radio' && !this.checked)
    {
        // this is a radio button, but it not checked, so skip it
        return;
    }
    formdata.append(this.name, $(this).val());
});
0

, , , .

var formData = new FormData();

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

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

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

All Articles