0

I have radio buttons that alert a different number depending on which one is selected.

var radioButtons = document.querySelectorAll('input[type=radio]');

var chanceoflive1 = 0;
var user;
function choose(choice){
    user = choice;
}

function changechanceoflive1(){
    if (user == 'bricks') {
        chanceoflive1 = 1;
    }
    else if (user == 'wood') {
        chanceoflive1 =3
    }
    else if (user == 'stone') {
        chanceoflive1 = 2
    }
    alert(chanceoflive1);
}
<div id="radiobuttons" class="container" name="buttons" align=center>

  <h2>I Want my Building to be Made of:</h2>

  <ul>
  <li>
    <input type="radio" id="brick-option" name="material" value="1" onClick="choose('bricks')" checked="checked">
    <label for="brick-option">Bricks</label>

    <div class="check"></div>
  </li>

  <li>
    <input type="radio" id="wood-option" name="material" value="3" onClick="choose('wood')">
    <label for="wood-option">Wood</label>

    <div class="check">
      <div class="inside"></div>
    </div>
  </li>

  <li>
    <input type="radio" id="stone-option" name="material" value="2" onClick="choose('stone')">
    <label for="stone-option">Stone</label>

    <div class="check">
      <div class="inside"></div>
    </div>
  </li>
  </ul>
</div>

<form action="chooseheight.html">
  <div class="wrapper">
    <button class="button" onClick="changechanceoflive1()" align=center>Submit</button>
  </div>
</form>

When I click wood, it alerts 3, which is perfect. When I click stone, it alerts 2, which is great. Although, when I click bricks, it alerts 0. Why?

2
  • 2
    Because it's on a click event, even though the first radio button is initially selected it was never clicked so it will show 0 until you actually click on it to select it. Commented Jan 4, 2017 at 2:05
  • 2
    why are you not using value and getting the radio that was selected? Commented Jan 4, 2017 at 2:25

2 Answers 2

1

Change line 2 to be var chanceoflive1 = 1; and all will work as expected. The initial radio button is preselected. Without clicking away from bricks and then back to bricks, chanceoflive1 remains as its initial value of 0.

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

1 Comment

Thanks! It'll be my answer!
0

That's because the user haven't actually chosen anything if he doesn't click on any of the checkbox. Since you want to make bricks the default option, you can call choose('bricks') at the end of your script, or just set var user = 'bricks'; in the variable declaration.

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.