Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 443
anita.kcx Avatar asked May 13 '26 02:05

anita.kcx


1 Answers

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?

like image 65
Andy Avatar answered May 15 '26 16:05

Andy



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!