简体   繁体   中英

JavaScript - Text won't change color when checkbox is ticked

This is my script:

<script type="text/javascript">
    "use strict";

    var chk = document.querySelector('termsChkbx');

    document.getElementsByName("termsChkbx").onclick = function() {textCol()};

    function textCol() 
    {
        if(chk.checked){
             document.getElementById("termsText").style.color = "black";
        }

    }

</script>

And this is the html/php that I'm trying to link it to.

<p style="color: #FF0000; font-weight: bold;" id="termsText">
    I agree to the terms and conditions
    <input type="checkbox" name="termsChkbx">
</p>

I need the color of the text to change to black when the checkbox is ticked and back to red when it isn't. I'm not sure where I am going wrong, any help is appreciated.

var chk = document.querySelector('input[name="termsChkbx"]');

The following code snippet works for me. You were not passing the correct id to be selected.

 "use strict"; var chk = document.querySelector('#termsChkbx'); document.getElementById("termsChkbx").onclick = function() {textCol()}; function textCol() { if(chk.checked){ document.getElementById("termsText").style.color = "black"; }else document.getElementById("termsText").style.color = "red"; }
 <p style="color: #FF0000; font-weight: bold;" id="termsText">I agree to the terms and conditions <input type="checkbox" name="termsChkbx" id="termsChkbx"></p>

You can use document.getElementsByName instead.

 "use strict"; var chk = document.getElementsByName('termsChkbx')[0]; document.getElementsByName('termsChkbx')[0].onclick = function() { textCol() }; function textCol() { if (chk.checked) { document.getElementById("termsText").style.color = "black"; } else { document.getElementById("termsText").style.color = "red"; } }
 <p style="color: #FF0000; font-weight: bold;" id="termsText">I agree to the terms and conditions <input type="checkbox" name="termsChkbx"></p>

Use querySelector("#termsText input") to be sure that the target is the input.

"use strict";

var chk = document.querySelector("#termsText input");

chk.onclick = function() {
  textCol()
};

function textCol() {
  var paragraph = document.getElementById("termsText");
  if (chk.checked) {
    paragraph.style.color = "black";
  } else {
    paragraph.style.color = "red";
  }
}

Consider simplifying your code:

 document.querySelector('.trmsChkbx').onclick = function() { document.querySelector(".trmsTxt").style.color = this.checked ? "#000" : "#f00"; }
 .trmsTxt{ color: #f00; font-weight: 700; }
 <label class="trmsTxt" id="trmsTxt"> I agree to the terms and conditions <input type="checkbox" name="trmsChkbx" class="trmsChkbx"> </label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM