1

I have the following problem. I have multiple checkboxes which I want to fill. I got an array with the selection from a form but i don't know how to check which of the checkboxes is the right one.

For my input a used something similar to this:

<input type="checkbox" id="zutaten" name="zutaten[]" value="a" >
<input type="checkbox" id="zutaten" name="zutaten[]" value="b" >
<input type="checkbox" id="zutaten" name="zutaten[]" value="c" >
<input type="checkbox" id="zutaten" name="zutaten[]" value="d" >

so I get an array 'zutaten', but this array isn't associative , so i don't know exactly which checkbox was checked. How should I solve this?

I can use PHP or Javascript/jQuery

2
  • Please post the array you've got. Commented Jan 11, 2013 at 15:19
  • doesn't the value get passed to the server too? Commented Jan 11, 2013 at 15:23

2 Answers 2

3

So you have an array with the $_POST response, let's say $zutaten=$_POST['zutaten'] for convenience.

Do the following for all 4 entries. You can do it dynamically if you have the possible values in an array, let me know if you need help with that.

<input type="checkbox" <?php if (in_array('b', $zutaten)) echo 'checked="checked"'; ?> id="zutaten" name="zutaten[]" value="b" >

EDIT: Don't forget to keep in $zutaten only the values that were checked. If you have an array. You can do the following:

$values = array('a', 'b', 'c', 'd');
foreach ($values as $val) {
    <input name="zutaten[]" value="<?php echo $val; ?>" type="checkbox" <?php if (in_array($val, $zutaten)) echo 'checked="checked"'; ?> 
}
Sign up to request clarification or add additional context in comments.

Comments

0

Do this:

<input type="checkbox" id="zutaten" name="zutaten[0]" value="a" >
<input type="checkbox" id="zutaten" name="zutaten[1]" value="b" >
<input type="checkbox" id="zutaten" name="zutaten[2]" value="c" >
<input type="checkbox" id="zutaten" name="zutaten[3]" value="d" >

Then you will see the numbers 0-3 in your array to decide which one was checked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.