2

Please help.

I am trying to dynamically name my checkboxes using php. I am using POST. The problem I am running in to is $element is not working. The results of $_POST does not show any checkboxes.

Thanks in advance for the help.

foreach(array_keys($cart_array) as $element)
{ 
    print "<input type = 'checkbox' checked name = '{$element}' />";
}

But something like

foreach(array_keys($cart_array) as $element)
{ 
    print "<input type = 'checkbox' checked name = '$element}' />";
}

works just fine. Notice the missing { near $element}. This code would show which checkboxes are on!! The printed array would have an extra "}"

Array
(
    [Tomato_and_Cheese_small] => on
    [Tomato_and_Cheese_small}] => 1
    [Tomato_and_Cheese_large] => on
    [Tomato_and_Cheese_large}] => 1
)

ps. there are other inputs like text that get posted to $_POST just fine. The print_r($cart_array) works fine too.

6
  • what are the contents of $cart_array? can you perform print_r($cart_array)? Commented Sep 4, 2011 at 19:10
  • and also, provide print_r($_POST). Commented Sep 4, 2011 at 19:13
  • Array ( [Tomato_and_Cheese_small] => 2 [Tomato_and_Cheese_large] => 1 ) Commented Sep 4, 2011 at 19:16
  • 1
    In your question you mention radio buttons, in your code sample you print checkboxes. Which one is causing problems? Commented Sep 4, 2011 at 19:16
  • OK, I have one other thing that I need you to perform to give you accurate answer, can you perform print_r($element) inside the foreach loop, I need to be sure what it contains. Commented Sep 4, 2011 at 19:26

3 Answers 3

1

The browser sends the value of radio buttons only when they are checked.

Also, each radio button must have the same name (if you want to user to be able to check only one of them). Only the value changes:

print '<input type=checkbox checked value="'.htmlspecialchars($element).'" name=checked_items />';

POST this and check the value of $_POST['checked_items']

Sign up to request clarification or add additional context in comments.

1 Comment

@ arnaud sorry, I was trying to say checkboxes and not radio buttons.
0

If a checkbox is not checked it will not be present in the post parameters.

1 Comment

Thanks. It is a checkbox that I am having trouble with and not the radiobutton.
0

What happened was that he had checkboxes with the name $element and text fields with the same name too after that. So the checkbox name $element in $_POST got overrided by the text field $element

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.