EvanGWatkins
EvanGWatkins

Reputation: 1457

jQuery get the value of radio buttons without page refresh

I have a set of radio buttons (individual buttons) in asp.net. These buttons have a group name (if that matters). What I need to happen is, anytime a user selects a radio button, I need some jQuery to be called. I am not doing a page refresh when the user selects the radio button, so I need this to be done on the fly. I have tried a "CheckedChanged" event in asp.net and can not get it to fire. I have also tried:

if ($('input:radio').attr('checked') === true) {
                  var checked = $('input:radio:checked').val();
              }

however it only works the first time the page is loaded, not when a user selects something other than the default. What Can I do to fix this?

Upvotes: 0

Views: 1660

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74227

Try something like this:

<p>
  <input type="radio" name="myRadioButtonSet" id="myRadioButtonSet1" value="1" /><label for="myRadioButtonSet1">&nbsp;One</label><br/>
  <input type="radio" name="myRadioButtonSet" id="myRadioButtonSet2" value="2" /><label for="myRadioButtonSet2">&nbsp;Two</label><br/>
  <input type="radio" name="myRadioButtonSet" id="myRadioButtonSet3" value="3" /><label for="myRadioButtonSet3">&nbsp;Three</label><br/>
</p>
<script type="text/javascript">
  $(function(){
    var oldValue = $('input:radio[name=myRadioButtonSet]:checked') ;
    $('input:radio[name=myRadioButtonSet]').click(function(){
      var newValue = $('input:radio[name=myRadioButtonSet]:checked').val() ;
      alert( 'old value:'+oldValue + ' / ' + 'new value:'+newValue ) ;
      oldValue = newValue ;
      return ;
    }) ;
    return ;
  }) ;
</script>

The click event occurs any time the radio button is clicked (even if the value doesn't change); the change event fires only when the value changes.

The closure (conveniently) has the oldValue variable still in scope, so you can track the state changes.

Upvotes: 0

Jack Marchetti
Jack Marchetti

Reputation: 15754

If you have AutoPostBack="true" than anytime the user selects a radiobutton the page will post back (refresh).

So set it to false, and handle the change event through jquery.

Upvotes: 0

Nick Spiers
Nick Spiers

Reputation: 2354

If you bind it to the change event it will fire every time the item is changed

$("input:radio").change(function(eventObject){
    var checked = $(eventObject).val();
});

Upvotes: 1

Related Questions