简体   繁体   中英

Javascript: Changing style with radio buttons without JQuery?

I have three radio buttons that are supposed to change font size. Each one has an id that designates what font size it changes to.

For some reason, I keep getting a "Uncaught Type Error: Cannot set property 'onchange' of null." I'm guessing that this is happening because sizeControl doesn't exist, but it clearly does. The variable is initialized and enclosed in window.onload = function() which means it isn't because the HTML isn't being loaded before the script (the only circumstance of this error that I know how to address).

Am I not supposed to use onchange in this particular circumstance? Is there an issue with the way I wrote the fontSizeChange function?

Radio Buttons:

 <label><input id="36pt" type="radio" name="size" checked="checked" />Medium</label>
 <label><input id="48pt" type="radio" name="size" />Big</label>
 <label><input id="60pt" type="radio" name="size" />Bigger</label>     


  var sizeControl = document.getElementById("size");
  sizeControl.onchange = fontSizeChange;

Function that attempts to change the size property of the display:

function fontSizeChange() {
  var display = document.getElementById("display");
  var fontChecked = [document.getElementById("36pt"),
    document.getElementById("48pt"),
    document.getElementById("78pt")
  ];
  for (var i = 0; i < fontChecked.length; i++) {
    if (fontChecked[i].checked == true) {
      display.style.fontSize = fontChecked[i].id;
    }
  }
  display.innerHTML = "String";
}

Try this

<!DOCTYPE html>
<html>
<body>

<label><input id="36pt" type="radio" name="size" />Medium</label>
<label><input id="48pt" type="radio" name="size" />Big</label>
<label><input id="60pt" type="radio" name="size" />Bigger</label>

<label id="display">String</label> 
<script>
var elements = document.getElementsByName("size");

for(var i=0; i < elements.length; i++){
  elements[i].addEventListener('click', fontSizeChange, false);
}


function fontSizeChange(){
   var display = document.getElementById("display");
   display.style.fontSize = this.id;
}
</script>

</body>
</html>

Your code in the question will only work once when the page loads, when the page loads the first radio button is selected then the font size will be always 36pt. There is no eventListener added to the radio button so when you click nothing will happen.

Here in My code am getting all the elements and adding a click eventListener and binding a function, so whenever a button is clicked this function will execute and this will refer to the button clicked. I hope you understood my explanation .

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