0

I have an order form with several checkbox input fields. I want to show the user the selection made before submitting the form. The js script shown bellow works as intended if the user checks a box the value of that box is showed in the paragraph. The problem is that every additional checked checkbox overrides the previous shown result.

How do I change the script to output all the checked checkbox?

This is the PHP form:

<input type="checkbox" onchange="toggleCheckbox(this)" value="1" name="1">
<input type="checkbox" onchange="toggleCheckbox(this)" value="2" name="2">
<input type="checkbox" onchange="toggleCheckbox(this)" value="3" name="3">
<input type="checkbox" onchange="toggleCheckbox(this)" value="4" name="4">
<input type="checkbox" onchange="toggleCheckbox(this)" value="5" name="5">
<input type="checkbox" onchange="toggleCheckbox(this)" value="6" name="6">
<input type="checkbox" onchange="toggleCheckbox(this)" value="7" name="7">

The JavaScript i use:

<script type="text/javascript"> 
    function toggleCheckbox(element){
        if (element.checked){
        document.getElementById("test").innerHTML = element.value;
        }
        else document.getElementById("test").innerHTML = "";
} 
</script>

The HTML field:

<p id="test"></p>
1

1 Answer 1

1

+= not =

    function toggleCheckbox(element){
       if (element.checked)
         document.getElementById("test").innerHTML += " " + element.value;
       else 
         document.getElementById("test").innerHTML = 
            document.getElementById("test").innerHTML.replace(element.value, "");
    } 
Sign up to request clarification or add additional context in comments.

2 Comments

That did the trick. Still, any idea how to change the else part to remove only the item that was unchecked?
Top class! Thanks a lot for the quick replies :D

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.