Array for Checkboxes in HTML Forms
1 . Both work, solution with lang[] is much more flexible. For example if you have really long form with a list of checkboxes in a few categories, eg. languages user speaks, countries he visited, cars he drove, and let's say each list consists of 10 elements, then hard coding every one of them is a pain in the ..., on PHP side you'd have to check every element manually, and with an array you can do this:
if (isset($_POST['lang'] && is_array($_POST['lang']){ // let's iterate thru the array foreach ($_POST['lang'] as $lang) { // do some super-magic here // in your example array elements would be $_POST['lang'] = array('en','fr','es') }}
2 . Like said above to check if any of the languages was selected check:
if (in_array('en', $_POST['lang']))
3 . If you are going to use jQuery simply use this snippet:
// selector ATTRIBUTE*=VALUE find all tags wchich ATTRIBUTE string contains VALUE$('input[name*=lang]').attr('checked', 'checked'); // check$('input[name*=lang]').removeAttr('checked'); // uncheck
Answers:
- Either works...depends on whether you want explicit names or an array
- You can also use
array_key_exists()
- Can you post the javascript code you are using into your question? I'll take a further look...
UPDATE:
Here is a jQuery solution for implementing your onclick handlers:
function checkAll(field){ $(':checkbox[name^="cuisine_"]').each(function(index){ this.checked=true; });}function uncheckAll(field){ $(':checkbox[name^="cuisine_"]').each(function(index){ this.checked=false; });}
Note that you really don't need to pass in field
, unless you want to generalize this and pass in the string for the startswith pattern (e.g. cuisine_
).