1

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 come 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.com",
        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?

14
  • 2
    have you tried using .serialize()? 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. Commented Nov 26, 2013 at 14:02
  • @Johan, how will the function know if the checkboxes have been checked? Commented Nov 26, 2013 at 14:03
  • @DrixsonOseña, unfortunately I'm a complete beginner with JSON and Jquery so what I have attempted is the result of extensive googling, can you explain what .serialize() does? Commented Nov 26, 2013 at 14:04
  • $(this).prop('checked'); will return a bool Commented Nov 26, 2013 at 14:15

2 Answers 2

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.com",
         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/ comments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?

Sign up to request clarification or add additional context in comments.

1 Comment

I've tried nearly 4 hours of googling results and only this worked straight! thank you for the good explanation and nicely done job :)
1

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.

2 Comments

Thanks, will this take both the textbox values and the checkbox values?
<textarea> element's tagName is 'textarea'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.