How to collect checked values in checkboxes as a javascript array/string?

10,448

Solution 1

Rather than

<form> 
<input type="checkbox" id="interests" name="interests[]" value="Food"> 
<input type="checkbox" id="interests1" name="interests[]" value="Movies"> 
<input type="checkbox" id="interests2" name="interests[]" value="Music"> 
<input type="checkbox" id="interests3" name="interests[]" value="Sports">

Change the name attribute from interests to interests[] Should solve your problem. If I am wrong about the attribute I am sorry, a little out of practice with PHP, but I am pretty sure. No need to do anything with javascript. Its much easier this way. Of course, if you don't want easy...

In terms of your first question about searching it through the database, I don't understand why you would need to?? If its a checkbox you know exactly what it should be, so just make it that and insert it into your database like so:

INSERT INTO your_table values(user_id_i_guess, interests...);

You get the point right?

Solution 2

Problems in your code

  • don't use same id to multiple elements

  • change checkboxs' name to interests[]

jQuery

var vals = [];

$(':checkbox:checked[name^=interests]').val(function() {
   vals.push(this.value);
});

If you want to convert array to as comma separated string then try

val.join(',');

Note

$(':checkbox:checked[name^=interests]') selector select all checked checkbox with name start with interests.

Share:
10,448
anita.kcx
Author by

anita.kcx

Updated on June 04, 2022

Comments

  • anita.kcx
    anita.kcx about 2 years

    I want to know how to search the inputs provided by the user in the form of checkboxes in a mysql database. But before that I need to get the checked fields into a javascript array/string so that I can pass it to PHP with the url.

    <form>
        <input type="checkbox" id="interests" name="interests" value="Food">`
        <input type="checkbox" id="interests" name="interests" value="Movies">`
        <input type="checkbox" id="interests" name="interests" value="Music">`
        <input type="checkbox" id="interests" name="interests" value="Sports">`
    </form>
    

    I am able to the above for other form elements such as text and select input but not sure how to do it for checkboxes. Please help. Thanks