Powered by Blogger.

How to get checked values and key pair of a checkbox which its name is an array?


If your checkbox name is an array with the key then you need to read the following to get checked values and key pair using jQuery.

The HTML source code of checkboxes is as the following.


<input type="checkbox" name="chk_array[678]" value="cat 1" />Cat 1
<input type="checkbox" name="chk_array[679]" value="cat 2" />Cat 2
<input type="checkbox" name="chk_array[689]" value="cat 3" />Cat 3
<input type="checkbox" name="chk_array[701]" value="cat 4" />Cat 4

jQuery codes as the following:

$("#submit_button_id").click(function(){
    var checkbox_obj = $( "[name^='chk_array']:checked" );
    var checkbox_data_obj = {};
    $(checkbox_obj).each(function(index, value){
        var chk_element = $(this).attr("name");
        key = chk_element.replace('chk_array[', '');
        key = key.replace(']', '');
        checkbox_data_obj[ key ] = $(this).val();
    });
});

If you are using ajax then you may post checkbox_data_obj to PHP directly then your PHP script will recognize it as PHP array.

Once done, checkbox_data_obj will be organised as checkbox_data_obj[679] = “cat 2”, checkbox_data_obj[689] = “cat 3” if Cat 2, Cat 3 checked.

No comments