Michael Ortiz
Michael Ortiz

Reputation: 777

Dynamically, check radio button with for loop

I'm trying to create a 5 star radio picker.

This is the 1 of the radio buttons:

<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">

After the method gets called and "3" is passed on this is my javascript function:

function check(stars)
{
    for(i = 0 ; i < stars; i++)
    {       
        document.getElementById("num_" + stars + "_star").checked = true;
    }   
}

When I run the code, it does not perform the checked to = true, though if remove the for loop, it works just fine.

Any ideas why the for loop is preventing from checking the radio boxes?

This is my entire code:

<script>
function check(stars)
{
    for(i = 0 ; i < stars; i++)
    {       
        document.getElementById("num_" + stars + "_star").checked = true;
    }   
}
</script>

<form>
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
</form>

Thanks!

Upvotes: 0

Views: 1825

Answers (2)

Rayon
Rayon

Reputation: 36609

i had to be 1 initially as ids are starting from 1

Also reset all the checked status when click is initiated! Use i instead of stars in getElementById

Try this:

function check(stars) {

  for (var j = 1; j <= 5; j++) {
	document.getElementById("num_" + j + "_star").checked = false;
  }
  for (var i = 1; i <= stars; i++) {
    document.getElementById("num_" + i + "_star").checked = true;
  }
}
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">

Upvotes: 2

mic4ael
mic4ael

Reputation: 8310

Put var before the iteration variable i. You are creating a global variable.

Upvotes: 1

Related Questions