如何动态计数没有。选中的单选按钮并在div中显示它们

时间:2017-08-19 20:05:55

标签: javascript jquery html

我的页面上有几个单选按钮,我想要的是每次选中或取消选中按钮时,都应该在网页上动态显示。



<div>
<h1>first part</h1>
 <input type ="radio" name="hope1" value="1">
 <input type ="radio" name="hope2" value="2">
 <input type ="radio" name="hope3" value="3">
<h2>second part</h2>
 <input type ="radio" name="hope1" value="4">
 <input type ="radio" name="hope2" value="5">
 <input type ="radio" name="hope3" value="6">
</div>

<div>
<h1> the no. of checkboxes selected are:"it should be displayed here"</h1> 
</div>
&#13;
&#13;
&#13;

我是javascript的新手,请提供一些解决方案。

1 个答案:

答案 0 :(得分:2)

您可以在change事件的输入上设置事件侦听器。为h1提供您要更改的ID,并使用.text()设置其文本。 $('input[type="radio"]:checked').length将提供多个已选中的单选按钮。像这样的东西:

&#13;
&#13;
$('input[type="radio"]').change(function(){
 $('#result').text("the no. of checkboxes selected are: " + $('input[type="radio"]:checked').length);
})
 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div>
<h1>first part</h1>
 <input type ="radio" name="hope1" value="">
 <input type ="radio" name="hope2" value="">
 <input type ="radio" name="hope3" value="">
<h2>second part</h2>
 <input type ="radio" name="hope1" value="">
 <input type ="radio" name="hope2" value="">
 <input type ="radio" name="hope3" value="">
</div>

<div>
<h1 id='result'> the no. of checkboxes selected are:"it should be displayed here"</h1> 
</div>
&#13;
&#13;
&#13;