简体   繁体   中英

Simple JS function doesn't work

Does anyone have an idea why my JS function is not working/my price div isn't showing anything at all?

HTML:

<div id="variant">
    <label><input type="radio" name="toggle" id="3"><span>A</span></label>
    <label><input type="radio" name="toggle" id="12" checked="checked"><span>B</span></label>
    <label><input type="radio" name="toggle" id="24"><span>C</span></label>
</div>
<br>
<div id="price"></div>

JS:

function setPrice() {
  if (document.getElementById('3').checked) {
    document.getElementById('price').innerHTML = "19,99€";
  } else if (document.getElementById('12').checked) {
    document.getElementById('price').innerHTML = "<<<";
  } else (document.getElementById('24').checked) {
    document.getElementById('price').innerHTML = "xxx";
  }
}

An "else" condition doesn't take in a statement, it would be IF / ELSE IF that takes in statements. Please see updated code snippet!

 function setPrice() { if (document.getElementById('3').checked) { document.getElementById('price').innerHTML = "19,99€"; } else if (document.getElementById('12').checked) { document.getElementById('price').innerHTML = "<<<"; } else if (document.getElementById('24').checked) { document.getElementById('price').innerHTML = "xxx"; } } setPrice(); 
 <div id="variant"> <label><input type="radio" name="toggle" id="3" onClick="setPrice();"><span>A</span></label> <label><input type="radio" name="toggle" id="12" onClick="setPrice();" checked="checked"><span>B</span></label> <label><input type="radio" name="toggle" id="24" onClick="setPrice();"><span>C</span></label> </div> <br> <div id="price"></div> 

The error comes from two sources.

  1. You aren't calling setPrice()
  2. Your line else (document.getElementById('24').checked) . There shouldn't be a condition if there isn't an if

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