Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
});
like image 583
Moltres Avatar asked Nov 10 '22 18:11

Moltres


1 Answers

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;
});
like image 176
CodingIntrigue Avatar answered Nov 14 '22 22:11

CodingIntrigue