1

I know it should be simple, but I couldn't find a way to do it and I have a feeling that is simple but I am stuck. I am trying to display a message every time a checkbox is checked. I have the code below but I can only display the message for the first checkbox. I am just starting with Javascript.

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";
    }
}
<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

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

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

Checkbox2: <input type="checkbox" id="myCheck"  onclick="myFunction()">

<p id="text" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck"  onclick="myFunction()">

<p id="text" style="display:none">Third checkbox is checked</p>



</body>
</html>

2
  • Same id is rule violation give class. Commented Mar 16, 2018 at 3:25
  • make the checkbox id unique. Commented Mar 16, 2018 at 3:28

8 Answers 8

1

id must be unique, You can pass id of both checkbox and p as parameter to function as follows,

function myFunction(id,pid) {
    var checkBox = document.getElementById(id);
    var text = document.getElementById(pid);
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
       text.style.display = "none";
    }
}
<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck1"  onclick="myFunction(this.id,'text1')">

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

Checkbox2: <input type="checkbox" id="myCheck2"  onclick="myFunction(this.id,'text2')">

<p id="text2" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck3"  onclick="myFunction(this.id,'text3')">

<p id="text3" style="display:none">Third checkbox is checked</p>



</body>
</html>

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

Comments

1

Not going to go on about the importance of why #IDs need to be unique and how that hobbles the expected behavior of the checkboxes. There are 2 demos:

Demo 1 uses JavaScript which is IMO overkill for a simple task.

  1. For event handling, try to avoid using on-event attribute event handlers:

    <div onclick="func();"></div>

    Try addEventListener() instead, follow the links for details.

  2. Event Delegation is used in Demo 1 so only the added <form> element is used as the eventListener instead of multiple checkboxes.

  3. An alternate way of referencing form controls (ex. input, textarea, etc) is by using the HTMLFormControlsCollection API. Wrapping inputs into an actual <form> tag and giving them #id and/or [name] attributes we can use a simple and short syntax. In this demo it really isn't needed but here's an example of a conventional way vs. event delegation/HTMLFCC:

    Normal way:

     var chxs = document.querySelectorAll('[type=checkbox]');
     for (let i = 0; i < chxs.length; i++) {
        chxs[i].addEventListener('change', message);
     }
    

    Event Delegation/HTMLFormControlsCollection

     var form = document.forms.formID;
    
     form.addEventListener('change', message);
    

Demo 2 uses CSS only.

  • Using two pseudo-classes:

    • :checked gives us two states to change styles like display:none/block.

    • + Adjacent Sibling Combinator allows us fine grain control of elements that immediately follow the checkbox (as well as additional siblings and descendant nodes if needed).


Details commented in Demos

Demo 1

// Reference the form - see HTMLFormControlsCollection
var chxGrp = document.forms.checkGroup;

/* Register the change event to form. 
|| Call message() function when a change event happens on or 
|| within the form.
|| A change event occurs when the user enters data (*input*) 
|| within a form control like an input (*focus*) then clicks onto
|| another (*unfocus*).
|| change event is different than most of the events because it
|| involves multple steps from the user, but it is very effective 
|| for form controls.
*/
chxGrp.addEventListener('change', message);

/* The Event Object is passed through, you might've seen it as 
|| "e" or "evt". How it's labelled doesn't matter because Event
|| Object is always available when you deal with the DOM.
*/
function message(event) {
  
  // if the node clicked is a checkbox see if it's...
  if (event.target.type === 'checkbox') {
  
    // ... checked then...
    if (event.target.checked) {
    
      // ...find the node that follows it (i.e. <b>)...
      event.target.nextElementSibling.className = "message";
    } else {
      /* Otherwise remove any class on it. (there's a more modern
      || method: classList that can be used instead)
      */
      event.target.nextElementSibling.className = "";
    }
  }
  return false;
}
b {
  display: none
}

label {
  display: table
}

[type=checkbox] {
  display: table-cell;
}

.message {
  display: table-cell;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
<!-- Wrapped the checkboxes with a <form> giving us opportunities: 
HTMLFormControlsCollection API for specialized referencing and
Event Delegation allowing us to use a single eventListener for an
unlimited amount of event.targets (clicked, changed, inputed, 
etc. buttons, links, etc.)-->
  <form id='checkGroup'>

    <p>Display some text when the checkbox is checked: </p>

    <label>Checkbox 1: <input type="checkbox">
  <b>Checkbox is CHECKED!</b>
  </label><br>

    <label>Checkbox 2: <input type="checkbox">
  <b>Second checkbox is checked</b>
  </label><br>

    <label>Checkbox 3: <input type="checkbox">
  <b>Third checkbox is checked</b>
  </label><br>

  </form>

</body>

</html>

Demo 2 - CSS Only

/* Default state of message tag */

b {
  display: none
}


/* Using label as a container that acts like a table */

label {
  display: table
}


/* Checkboxes are normally set as a component that sits inline
with their siblings. Acting as a table-cell does that and has
additional advantages as well. 
When the checkbox is :checked...
The adjacent sibling + <b> behaves as a table-cell as well,
thereby being shown/hidden by the corresponding checkbox being
toggled.
*/

[type=checkbox],
[type=checkbox]:checked + b {
  display: table-cell;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <!-- Layout has been slightly re-arranged to take advantage of 
styling combonations and tag behavior -->
  <p>Display some text when the checkbox is checked: </p>

  <label>Checkbox 1: <input type="checkbox">
  <b>Checkbox is CHECKED!</b>
  </label><br>

  <label>Checkbox 2: <input type="checkbox">
  <b>Second checkbox is checked</b>
  </label><br>

  <label>Checkbox 3: <input type="checkbox">
  <b>Third checkbox is checked</b>
  </label><br>



</body>

</html>

Comments

0

You have multiple elements with the same ID. Try changing two ID's to have either a number on the end (myCheck 1 or myCheck2), or change it to something else completely. Here's my suggestion:

function myFunction(idCheck, idText) {
    var checkBox = document.getElementById(idCheck);
    var text = document.getElementById(idText);
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
       text.style.display = "none";
    }
}
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck"  onclick="myFunction('myCheck', 'text')">

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

Checkbox2: <input type="checkbox" id="myCheck1"  onclick="myFunction('myCheck1', 'text1')">

<p id="text1" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck2"  onclick="myFunction('myCheck2', 'text2')">

<p id="text2" style="display:none">Third checkbox is checked</p>



</body>
</html>

Comments

0

First you need to have input type checkbox with uniq id.

<input type="checkbox" id="uniq_id" />

Then in script, call your function

$("#uniq_id").click( function(){
  if( $(this).is(':checked') ){ 
     //call your function here
     myFunction(this);  
   }
});

Comments

0

id need to be unique. Pass the id through the onclick handler using this.id

function myFunction(id) {
  var checkBox = document.getElementById(id);
  var text = document.getElementById("text");
  if (checkBox.checked === true) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction(this.id)">

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

Checkbox2: <input type="checkbox" id="myCheck2" onclick="myFunction(this.id)">

<p id="text" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck3" onclick="myFunction(this.id)">

<p id="text" style="display:none">Third checkbox is checked</p>

Comments

0

Well, since id is unique identifier your function always selects first checkbox.

document.getElementById("myCheck");

You need to modify it to smth. like this

<!DOCTYPE html>
<html>
<body>

    <p>Display some text when the checkbox is checked:</p>
    Checkbox:
    <input type="checkbox" id="check_1" onclick="myFunction(event)">
    <p id="text_check_1" style="display:none">Checkbox is CHECKED!</p>

    Checkbox2:
    <input type="checkbox" id="check_2" onclick="myFunction(event)">
    <p id="text_check_2" style="display:none">Second checkbox is checked</p>

    Checkbox3:
    <input type="checkbox" id="check_3" onclick="myFunction(event)">
    <p id="text_check_3" style="display:none">Third checkbox is checked</p>

    <script>
        function myFunction(event) {
            var checkBox = event.target,
                id = checkBox.id,
                text = document.getElementById("text_" + id);
            if (checkBox.checked == true) {
                text.style.display = "block";
            } else {
                text.style.display = "none";
            }
        }
    </script>
</body>
</html>

Comments

0

Indeed you have to use different IDs, also you don't need several p elements for that and lastly to avoid unnecessary queries, you could pass the clicked element to the function since you are calling it via the onclick attr.

function myFunction(elem) {
    var checkBox = elem;
    var p = document.getElementsByTagName('p')[1];
    if (checkBox.checked == true){
        p.innerHTML = "Checkbox <b>" + checkBox.id + "</b> is CHECKED!"
        p.style.display = "block";
    } else {
       p.style.display = "none";
    }
}
<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck1"  onclick="myFunction(this)">

<p class="text" style="display:none"></p>

Checkbox2: <input type="checkbox" id="myCheck2"  onclick="myFunction(this)">

Checkbox3: <input type="checkbox" id="myCheck3"  onclick="myFunction(this)">

</body>
</html>

HIH

Comments

0

You don't need javascript or jquery at all - this can be achieved using CSS alone - using the direct sibling selector and the :checked pseudo selector you can set the display or visibility property on the next p.

You did have multiple id's so that needs to be corrected - but CSS is all you need to toggle the next p after the checked checkbox.

p{display: none}
input[type="checkbox"]:checked + p {display: block}
<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck1">
<p>First Checkbox is CHECKED!</p>

Checkbox2: <input type="checkbox" id="myCheck2">

<p>Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck2">

<p>Third checkbox is checked</p>

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.