简体   繁体   English

动态地检查带有for循环的单选按钮

[英]Dynamically, check radio button with for loop

I'm trying to create a 5 star radio picker. 我正在尝试创建5星收音机选择器。

This is the 1 of the radio buttons: 这是单选按钮中的1个:

<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: 在调用方法并传递“ 3”之后,这是我的javascript函数:

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. 当我运行代码时,它不会执行checked = true,尽管如果删除了for循环,它也可以正常工作。

Any ideas why the for loop is preventing from checking the radio boxes? 为什么for循环阻止检查单选框的任何想法?

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! 谢谢!

i had to be 1 initially as ids are starting from 1 i最初必须是1,因为ids是从1开始

Also reset all the checked status when click is initiated! 启动点击时,还要重置所有checked状态! Use i instead of stars in getElementById getElementById使用i代替stars

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

Put var before the iteration variable i . var放在迭代变量i之前。 You are creating a global variable. 您正在创建一个全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM