最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing checkbox values as JSON in Jquery - Stack Overflow

programmeradmin3浏览0评论

I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has e to my attention that this wont work for checkbox values. Here is my function:

<script>
console.log(document);
var form = document.getElementById("myform");

form.onsubmit = function (e) {
    // stop the regular form submission
    e.preventDefault();

    // collect the form data while iterating over the inputs
    var info = {};
    for (var i = 0, ii = form.length; i < ii; ++i) {
        var input = form[i];
        if (input.name) {
            info[input.name] = input.value;
        }
        addPerson(info);
    }
}

function addPerson(info) {
    $.ajax({
        type: "POST",
        url: "",
        data: JSON.stringify(info),
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        dataType: "json",

        success: function (data, status, jqXHR) {
            alert("success");
        },

        error: function (jqXHR, status) {
            // error handler
            console.log(jqXHR);
        }
    });
}
</script>

I've been trying to get the checkbox values into JSON using

$.each($('input[id="data[i].id"]:checked'), function() {
    var value = $(this).val();
    qualifications.push(value);
});

but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?

I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has e to my attention that this wont work for checkbox values. Here is my function:

<script>
console.log(document);
var form = document.getElementById("myform");

form.onsubmit = function (e) {
    // stop the regular form submission
    e.preventDefault();

    // collect the form data while iterating over the inputs
    var info = {};
    for (var i = 0, ii = form.length; i < ii; ++i) {
        var input = form[i];
        if (input.name) {
            info[input.name] = input.value;
        }
        addPerson(info);
    }
}

function addPerson(info) {
    $.ajax({
        type: "POST",
        url: "http://example.",
        data: JSON.stringify(info),
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        dataType: "json",

        success: function (data, status, jqXHR) {
            alert("success");
        },

        error: function (jqXHR, status) {
            // error handler
            console.log(jqXHR);
        }
    });
}
</script>

I've been trying to get the checkbox values into JSON using

$.each($('input[id="data[i].id"]:checked'), function() {
    var value = $(this).val();
    qualifications.push(value);
});

but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?

Share Improve this question edited Nov 26, 2013 at 13:59 Jonathan Naguin 14.8k6 gold badges51 silver badges76 bronze badges asked Nov 26, 2013 at 13:56 bookthiefbookthief 2,4618 gold badges42 silver badges55 bronze badges 14
  • 2 have you tried using .serialize()? – Drixson Oseña Commented Nov 26, 2013 at 13:59
  • I don't see why checkboxes should be a problem, they have a value property just like any other form element. – Johan Commented Nov 26, 2013 at 14:02
  • @Johan, how will the function know if the checkboxes have been checked? – bookthief Commented Nov 26, 2013 at 14:03
  • @DrixsonOseña, unfortunately I'm a plete beginner with JSON and Jquery so what I have attempted is the result of extensive googling, can you explain what .serialize() does? – bookthief Commented Nov 26, 2013 at 14:04
  • $(this).prop('checked'); will return a bool – Johan Commented Nov 26, 2013 at 14:15
 |  Show 9 more ments

2 Answers 2

Reset to default 4

Have tried .serialize() and I THINK it is working-

<script>

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('myform').submit(function() {
        $('#result').text(JSON.stringify($('myform').serializeObject()));
        return false;
    });
});


function addPerson(result){
  $.ajax({
         type: "POST",
         url: "http://example.",
         data: JSON.stringify(result),
         contentType: "application/json; charset=utf-8",
         crossDomain: true,
         dataType: "json",

         success: function (data, status, jqXHR) {

             alert("success");
         },

         error: function (jqXHR, status) {
             // error handler
             console.log(jqXHR);

         }
      });
  }




</script>

If anyone has thoughts/ ments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?

Try this:

var input = form[i];
if (input.name) {
    if(input.tagName.toLowerCase() === 'input' && 
       (input.type.toLowerCase() === 'checkbox' || input.type.toLowerCase() === 'radio') &&
       input.checked)
         info[input.name] = input.value;
    else
       info[input.name] = input.value;
}
addPerson(info);

EDIT:

I suggest using jQuery form.serialize() method as @Drixson Oseña mentioned.

发布评论

评论列表(0)

  1. 暂无评论