Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass multiple checkbox values with one name?

I'm using Twitter's bootstrap and need to pass a delimited list of checkbox selections to my server for processing. The checkbox HTML looks like this:

<div class="controls">
    <label class="checkbox"><input type="checkbox" name="my_match[]" value="190">TEST 190</label>
    <label class="checkbox"><input type="checkbox" name="my_match[]" value="200">TEST 200</label>
    <label class="checkbox"><input type="checkbox" name="my_match[]" value="210">TEST 210</label>
</div>

...

$.post("form.php", $("#form_id").serialize(), function(){
    ...
});

I'm passing the form values as a serialized string using jquery but the values are being sent like so:

my_match=190&my_match=200

Is it possible to send them in the following format?

my_match=190:200

I'm not sure if I need to change my HTML or this is something I need to handle with javascript. Any thoughts?

like image 326
Paul Avatar asked May 12 '12 01:05

Paul


People also ask

Can multiple checkbox can have same name?

If a set of checkboxes have the same name the HTML form encoding is different to those with different names.

Should checkboxes have the same name?

Check boxes allow the user to select one or more options. Each check box must have a unique name. Radio buttons allow only one choice within a group of buttons. Each radio button within a group should have the same name.

Can a checkbox have two values?

Checkbox is used to make a choice between two options. Input from each checkbox is made to a single variable. A checkbox can pass one of the two values to this variable - one value for the checked state and another one for the unchecked state.


2 Answers

I believe checkboxes with the same name return back with a comma separated list. What you could do is create a hidden field, append your checked checkbox values the way you want and then send the hidden field instead.

like image 38
Chase Avatar answered Oct 21 '22 01:10

Chase


Something like this would do the trick:

<div class='controls'>
    <label class="checkbox">
        <input type="checkbox" name="my_match[]" value="190">TEST 190</label>
    <label class="checkbox">
        <input type="checkbox" name="my_match[]" value="200">TEST 200</label>
    <label class="checkbox">
        <input type="checkbox" name="my_match[]" value="210">TEST 210</label>
</div>

<form>
    <input id='my_match' type='hidden' name='my_match[]' />
    <button>Submit</button>
</form>

$('form').submit(function() {
    var arr=[];

    $('input:checked[name=my_match[]]').each(function(){
        arr.push($(this).val());
    });

    $('#my_match').val(arr.join(':'));
    alert($('#my_match').val());

    // Prevent actual submit for demo purposes:
    return false;
});
​
​

​ Try out the fiddle


Edit: This is basically exactly what Chase described in his answer.

like image 68
namuol Avatar answered Oct 21 '22 00:10

namuol