2

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?

2
  • when you submit the form, the selected item will be sent. Commented Aug 12, 2013 at 8:12
  • I'm assuming based on the code that you are using jQuery or is that some other library that uses the "$"? Commented Aug 12, 2013 at 8:12

3 Answers 3

10

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()
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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

Comments

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.