Fabian Raum
Fabian Raum

Reputation: 1

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";
  }
}

Upvotes: 0

Views: 123

Answers (2)

Howzieky
Howzieky

Reputation: 829

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

Upvotes: 0

Woodrow
Woodrow

Reputation: 2832

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>

Upvotes: 2

Related Questions