1

function myFunction(){
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
    text.style.display = "none";
}}
Checkbox 1: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 1 is CHECKED!</p>
<br>
Checkbox 2: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 2 is CHECKED!</p>

I want both check boxes to work after clicking one by one on it. The result I get: only checkbox 1 is working, the other is not working.

2 Answers 2

3

id attribute has to be unique so in this case getElementById only selects the first element. you can change the id attribute to class and then select your checkboxes and paragraphs with getElementsByClassName.

Checkbox 1: <input type="checkbox" class="myCheck" onclick="myFunction()">

<p class="text" style="display:none">Checkbox 1 is CHECKED!</p>
<br>
Checkbox 2: <input type="checkbox" class="myCheck" onclick="myFunction()">

<p class="text" style="display:none">Checkbox 2 is CHECKED!</p>

Now the JavaScript part need to recognize the checkboxes. We should add a FOR loop to select the checkbox[i] and the paragraph below it.

for (var i=0;i<checkBox.length; i++) {
    if (checkBox[i].checked == true){
    text[i].style.display = "block";
  } else {
    text[i].style.display = "none";
  }
} 

See the Demo here

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

Comments

2

Give different Id .It will works.

function myFunction(){
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
    text.style.display = "none";
}}

function myFunction1(){
  var checkBox = document.getElementById("myCheck1");
  var text1 = document.getElementById("text1");
  if (checkBox.checked == true){
    text1.style.display = "block";
  } else {
    text1.style.display = "none";
}}
Checkbox 1: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 1 is CHECKED!</p>
<br>
Checkbox 2: <input type="checkbox" id="myCheck1" onclick="myFunction1()">

<p id="text1" style="display:none">Checkbox 2 is CHECKED!</p>

2 Comments

If it is work for you then please up-vote and accept the answer.
unable to upvote --> thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.

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.