1

I have problem on the checkbox submission. The code is as below:

JavaScript

function init () {
    document.getElementById("pizza").topping[0].checked=true;
    document.getElementById("btn").onclick=poll;
}
onload = init;

function poll () {
    var i, isOK, summary="";
    var form=document.getElementById("pizza");
    for (i=0; i < form.topping.length; i++) {
        if (form.topping[i].checked) {
            summary+=form.topping[i].value+" ";
        }
    }
    isOK = confirm("Submit these choices?\n" + summary);
    if (isOK) {
        form.submit();
    } else {
        return false;
    }
}

HTML

<form id="pizza" action="poll.php" method="POST">
    <div id="panel">Pizza Topping?
        <input type="checkbox" name="topping" value="Cheese">Cheese</input>
        <input type="checkbox" name="topping" value="Ham">Ham</input>
        <input type="checkbox" name="topping" value="Peppers">Peppers</input>
        <input id="btn" type="button" value="Confirm Choices"></input>
    </div>
</form>

poll.php

<?php
    echo "<br>***************<br>";
    var_dump($_POST);
    echo '*********************';
?>

The JS confirm message: Submit these choices? Cheese Peppers

The output of poll.php:


array (size=1) 'topping' => string 'Peppers' (length=7)


So my problem is: I checked Cheese and Peppers but I only got Peppers submitted. Can anyone help me?

3
  • can you show ur server side code? Commented Jun 2, 2015 at 3:41
  • In the future, please consider properly formatting your code. Commented Jun 2, 2015 at 3:47
  • @Alex:I am practicing JavaScript, so I don't have server side code actually. Commented Jun 2, 2015 at 4:26

1 Answer 1

3

Give an array like name(with the suffix []) to the input elements

<input type="checkbox" name="topping[]" value="Cheese">Cheese</input>
<input type="checkbox" name="topping[]" value="Ham">Ham</input>
<input type="checkbox" name="topping[]" value="Peppers">Peppers</input>
Sign up to request clarification or add additional context in comments.

5 Comments

what is "array line name"?
Can you explain ur code a bit why are you doing topping[]?
@Arun, thanks for your answer. I tried your code, the line below doesn't work.document.getElementById("pizza").topping[0].checked=true; and the confirm button doesn't work.
document.getElementById("pizza")['topping[]'][0].checked=true;
@Arun: I made a mistake. I did not delete the dot between ("pizza") and ['topping[]'].

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.