JavaScript为所有后续单选按钮创建全局单选按钮?

时间:2012-06-25 15:33:45

标签: javascript jquery html radio-button

我有这组标签和单选按钮,如下所示:

Entertainment: <input type="radio" name="entertainment" id="entertainment" value="0" checked/>
               <input type="radio" name="entertainment" id="entertainment" value="1" /> 
               <input type="radio" name="entertainment" id="entertainment" value="2" /><br />


Radio: <input type="radio" name="radio" id="radio" value="0" checked/>
       <input type="radio" name="radio" id="radio" value="1" /> 
       <input type="radio" name="radio" id="radio" value="2" /><br />

Dancing: <input type="radio" name="dancing" id="dancing" value="0" checked/>
         <input type="radio" name="dancing" id="dancing" value="1" /> 
         <input type="radio" name="dancing" id="dancing" value="2" /><br />

Music: <input type="radio" name="music" id="music" value="0" checked/>
       <input type="radio" name="music" id="music" value="1" /> 
       <input type="radio" name="music" id="music" value="2" /><br />

Television: <input type="radio" name="tv" id="tv" value="0" checked/>
            <input type="radio" name="tv" id="tv" value="1" /> 
            <input type="radio" name="tv" id="tv" value="2" /><br />

Film: <input type="radio" name="film" id="film" value="0" checked/>
      <input type="radio" name="film" id="film" value="1" /> 
      <input type="radio" name="film" id="film" value="2" /><br />

Theatre: <input type="radio" name="theatre" id="theatre" value="0" checked/>
         <input type="radio" name="theatre" id="theatre" value="1" /> 
         <input type="radio" name="theatre" id="theatre" value="2" />

这个想法是顶部的三个“娱乐”单选按钮控制下面的所有单选按钮。如果你愿意的话,一个'全球开关'可以节省人们的时间。有没有人知道必要的JavaScript / jQuery来实现这一目标?我在网上找不到正确的例子。

1 个答案:

答案 0 :(得分:1)

$(':radio[name=entertainment]').change(function() {
  $(this).nextAll(':radio[value="'+ this.value +'"]').prop('checked', true);
  $(this).nextAll(':radio[value!="'+ this.value +'"]').prop('checked', false);
});

<强> Working sample

注意

id应该是唯一的。