Вопрос

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

Это было полезно?

Решение

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"'; ?> 
}

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top