pyrogrammer pyrogrammer - 1 month ago 9
HTML Question

How to dynamically count no. of selected radio buttons and show them inside a div

I've several radio buttons on my page, what i want is every time a button is checked or unchecked, it should be dynamically displayed on the web page.



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





I am really new to javascript, please provide some solution.

Dij Dij
Answer Source

you can set an event listener on inputs for change event. give an id to h1 that you want to change and set its text using .text(). $('input[type="radio"]:checked').length will give number of checked radio buttons. something like this:

$('input[type="radio"]').change(function(){
 $('#result').text("the no. of checkboxes selected are: " + $('input[type="radio"]:checked').length);
})
 
<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>