Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
fragon Avatar asked Dec 30 '25 17:12

fragon


1 Answers

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()
like image 105
Arun P Johny Avatar answered Jan 01 '26 08:01

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!