Moltres
Moltres

Reputation: 610

How to trigger event when a radio button is checked in jQuery

I tried doing this.So, when I click on the radio button, the code works but the radio button doesn't get checked and it remains normal. How to solve this?

<p>
    <input id="play" class="rad" type='radio' name='a'/>
    <input id="pause" class="rad" type='radio' name='a'/>
</p>
var output = $('h1');
var isPaused = false;
var time = 30;
var t = window.setInterval(function () {
    if (!isPaused) {
        time--;
        output.text("0:" + time);
    }
}, 1000);

//with jquery
$('.pause').on('click', function (e) {
    e.preventDefault();
    isPaused = true;
});

$('.play').on('click', function (e) {
    e.preventDefault();
    isPaused = false;
});

Upvotes: 5

Views: 1620

Answers (3)

Rasel
Rasel

Reputation: 5734

<input id="play" class="rad" type='radio' name='a' value="1"/>
    <input id="pause" class="rad" type='radio' name='a' value="2"/>

var output = $('h1');
var isPaused = false;
var time = 30;
var t = window.setInterval(function() {
    if(!isPaused) {
        time--;
        output.text("0:" + time);
    }
}, 1000);

//with jquery
$('.rad').on('change', function(e) {
    e.preventDefault();
    if(this.value=='2')
    isPaused = true;
    else
        isPaused = false;
});

fiddle

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

A few things:

Your selectors are wrong: $('.pause') should either be $("#pause") or $(".rad")

Also, you are calling e.preventDefault() inside click. This is preventing the default behavior of a click on a radio button, which is to check it.

Updated jsFiddle for what I think you're trying to achieve, which is to let the radio buttons be a toggle for your timer:

var output = $('h1');
var isPaused = false;
var time = 30;
var t = window.setInterval(function() {

    if(!isPaused) {
        time--;
        output.text("0:" + time);
    }
}, 1000);

//with jquery
$('#pause').on('click', function(e) {
    isPaused = true;
});

$('#play').on('click', function(e) {
    isPaused = false;
});

Upvotes: 1

void
void

Reputation: 36703

$("input[type=radio]").change(function(){

   if(this.checked) 
   {
     alert("checked");
   }

});

And if your radio button has id say play then directly use #play as selector i.e. $("#play").change().

Upvotes: 0

Related Questions