fragon
fragon

Reputation: 3471

How can I send checkboxes data into JSON array?

I'm new to .js and I have a problem with exporting answers from .js checkboxes form into JSON array.

My HTML:

<form>
<input type="checkbox" name="Question1" id="Answer1" value="Answer1" onclick="show_checked()"/><label for="Answer1">Answer 1</label><br/>
<input type="checkbox" name="Question1" id="Answer2" value="Answer2" onclick="show_checked()"/><label for="Answer2">Answer 2</label><br/>
<input type="checkbox" name="Question1" id="Answer3" value="Answer3" onclick="show_checked()"/><label for="Answer3">Answer 3</label><br/>
</form>

my Javascript:

function set_checked(checked) 
    $('input[name=foo]').attr('checked', checked);
}
$(document).ready(function () {
            $("input[name='Question1']").change(function () {
                var maxAllowed = 2; 
                var cnt = $("input[name='Question1']:checked").length;
                if (cnt > maxAllowed) {
                    $(this).prop("checked", "");
                    alert('Choose max. ' + maxAllowed + ' answers');
                }
            });
        });

The question is, how can I send IDs or values of the checked checkboxes into JSON array?

Upvotes: 2

Views: 23355

Answers (3)

cssyphus
cssyphus

Reputation: 40076

Comet's answer didn't work for me. This did:

var arrCB = {};

$("input[name='Question1']:checked").each(
    function(){
        var id = this.id;
        arrCB[id] = (this.checked ? 1 : 0)
    }
);

var text = JSON.stringify(arrCB);
alert(text);

Resources:

http://blog.kevinchisholm.com/javascript/associative-arrays-in-javascript/

best practice for updating a list in database associated with checkboxes in a html form

How can I send checkboxes data into JSON array?

JQuery: Turn array input values into a string optimization

Upvotes: 1

U.P
U.P

Reputation: 7442

See if this piece of code helps

var objArray = [];
$("input[name='Question1']:checked").each(function (index, elem) {
    var id = $(this).attr('id');
    var val = $(this).val();
    var obj = {
        Id = id,
        Value = val
    };
    objArray.push(obj);
});

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388366

to get values to an array

var array =  $("input[name='Question1']:checked").map(function(){
    return this.value;
}).get()

to get ids to an array

var array =  $("input[name='Question1']:checked").map(function(){
    return this.id;
}).get()

Upvotes: 10

Related Questions