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?
.serialize()?valueproperty just like any other form element.$(this).prop('checked');will return a bool