Nick Nick Nick Nick - 21 days ago 5
jQuery Question

jquery radiobutton doesn't fire event at first click

https://jsfiddle.net/8g94ykta/

Radiobutton fire event only at second/third click and only show only first result. How to fix it? Thank you.

<input type="radio" name="group" checked="checked" value="first">A
<input type="radio" name="group" value="second">B
<input type="radio" name="group" value="third">C
<p>
<span id="result">-</span>
</p>



$('input[type="radio"][name=group]:checked').click(function(){
if (this.value=='first') {
$("#result").text("first value");}
else if (this.value=='second') {
$("#result").text("second value");}
else if (this.value=='third') {
$("#result").text("third value");}

});

Answer

Please try this: $('input[type="radio"][name=group]') instead $('input[type="radio"][name=group]:checked')

You need to trigger the click event for all radio elements

$('input[type="radio"][name=group]').click(function(){
   if (this.value=='first') {
      $("#result").text("first value");}
   else if (this.value=='second') {
      $("#result").text("second value");}
   else if (this.value=='third') {
      $("#result").text("third value");}                
});