Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an event just before the radio button is about the be checked

Tags:

jquery

This is the part of the code for one of the radio buttons:

$("#new").click(function(){
    if( $('#new').is(':checked') )
        $.jGrowl("You already have this option selected!", life: 1500});
    else
        changeOption(1);
});

Now, I understand that the else part will never run, because the radio button will be already checked on click event. What I'm wondering is, is there an event which would let me capture the state of the radio button (which is about to be clicked) and therefor determine if he is not yet clicked, and if so change the option to this newly selected one.

like image 805
Nikola Avatar asked Dec 15 '22 20:12

Nikola


1 Answers

Store the initial value in a data attribute, and use that on changes:

$.each($("input[type='radio']"), function(i,e) {
    $(e).data('check', e.checked);
});

$("#new").on('click keyup', function(){
    if( $(this).data('check') ) {
        alert("You already have this option selected!");
    }else{
        alert("This option is unselected");
    }
    $(this).data('check', this.checked);
});​

FIDDLE

Even works with keyboard events.

like image 57
adeneo Avatar answered Apr 29 '23 00:04

adeneo