0

I'm attempting to display the names of my checkboxes with the foreach statement below, but all I'm getting is "on" for each one checked. I've got the code for one of the checkboxes and was wondering if there is anything I can change in it to make this work.

if(!empty($_POST['OUSdrop'])){
    foreach($_POST['OUSdrop'] as $check){
        echo $check;
    }
}


<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="UKSen">
    <input type="checkbox" id="UKSen" name="OUSdrop[]" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label" value="UK">United Kingdom</span>
</label>
1
  • You have set the value of checkbox in span tag. Move it to the input tag Commented Jun 26, 2017 at 15:21

3 Answers 3

1

why don't change it as

<input type="checkbox" id="UKSen" name="OUSdrop[UK]" class="mdl-
checkbox__input">

so that you know which one you want to set?

And also change the loop

foreach($_POST['OUSdrop'] as $check => $value){
        echo $check.':'.$value;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

if(!empty($_POST['OUSdrop'])){

    foreach($_POST['OUSdrop'] as $check => $value){
        echo $check;

    }
}

HTML CODE

<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="UKSen">
        <input type="checkbox" id="UKSen" name="OUSdrop[HERE]" class="mdl-checkbox__input">
        <span class="mdl-checkbox__label" value="UK">United Kingdom</span>
</label>

$check will contain the key ans $value the value.

3 Comments

All I got from that was 012 instead of ononon, and the checkboxes I selected weren't in those positions in the array
it's because your OUSdrop[] is a PHP array that contains indexes of any value stored in it.
Ended up having to access the $value option after changing the checkbox thanks to your update and that worked!
0

You have set the value in span tag which should be in input

When value is not defined most browsers will default to value="on" which means that it's 'on' (checked)

if (! empty($_POST['OUSdrop'])) {
    foreach($_POST['OUSdrop'] as $check) {
        echo $check;
    }
}


<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="UKSen">
    <input type="checkbox" 
           id="UKSen" 
           name="OUSdrop[]" 
           class="mdl-checkbox__input"  
           value="UK">
    <span class="mdl-checkbox__label">United Kingdom</span>
</label>

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.