0

I'm not sure why this function is not working. I have a bit of logic works fine, but when I tried to move that into a function it didn't work! No idea why!!

Please look at my code:

function check_checkbox_value($value) {
    if (!empty($value)) {
        return "checked";
    }
}

?>

<form method="get" action="">
    <br />Upper: <input type="checkbox" name="upper" <?php if (!empty($_GET['upper'])) { echo 'checked';} ?>>
    <br />Lower: <input type="checkbox" name="lower" <?php echo check_checkbox_value($_GET['lower']); ?>>
    <input type="submit" name="submit" value="Generate">
</form>

It's clear that the first input (upper) works (no Notice: Undefined index error when it's not checked/set), However the second input display the error when it's not set, I thought I moved that functionally to a function and returned the checked value and echo it.

Why the function doesn't work? Any ideas? Thank you so much!

  • If you're getting `undefined` you need to test for `isset()` – Jay Blanchard Jan 03 '17 at 14:13
  • @JayBlanchard Please reopen this question, the logic works already, it's just when I move it into a function it stops working, same logic I assume. The link you posted doesn't answer this specifically. Thank you. – user7369758 Jan 03 '17 at 14:19
  • You're not defining `value=` for the checkboxes. – Jay Blanchard Jan 03 '17 at 14:21
  • @JayBlanchard I did add it before and again but still not working when I call the function (value="" value="1" value="0"). Please note that without the value attribute I don't see the error when I check if the $_GET is not empty, it's just not working when I move it to the function. Thank you for you assistance. – user7369758 Jan 03 '17 at 14:30
  • Without `value=` your markup would not be valid and clicking submit would show 'on' for the checkbox values. See https://jsfiddle.net/nLwzpy4y/ and open your console to see the results when you run this. – Jay Blanchard Jan 03 '17 at 15:59
  • http://stackoverflow.com/questions/4260918/why-do-html-checkboxes-only-transmit-an-on-value – Jay Blanchard Jan 03 '17 at 16:06
  • http://stackoverflow.com/questions/11424037/does-input-type-checkbox-only-post-data-if-its-checked – Jay Blanchard Jan 03 '17 at 16:06

0 Answers0