开发者

Prevent radio button check and show an alert

开发者 https://www.devze.com 2023-03-06 09:31 出处:网络
I\'m trying to show an alert if a certain radio button in a group is checked and then to check the previously checked radio button again.

I'm trying to show an alert if a certain radio button in a group is checked and then to check the previously checked radio button again.

I was thinking of two solutions:

  1. Adding a disabled attribute, but click events are then not fired so I can't pop up an alert.

  2. If I don't add a disabled attribute, then the checked radio button has already changed inside the click event so I can't obtain the original checked radio button which I'd like to check again.

Basically, what I currently have is this: http://jsfiddle.net/Jygmn/2/

<input name="r" type="radio" id="r1"> r1<br>
<input name="r" type="radio" id="r2"> r2<br>
<input name="r" type="radio" id="r3"> r3<br>
<input name="r" type="radio" id="r4" disabled> r4<br>

JavaScript:

$('#r3, #r4').click(function() {
    window.alert($('input[name=r]:checked').attr(开发者_StackOverflow社区'id'));
    // 1) doesn't alert for #r4 because it's disabled.
    // 2) always alerts r3 when #r3 is clicked but I'd like to
    //    obtain the formerly checked radio button id.
});

How can I obtain the formerly checked radio button in the click event of #r3 (or is there something like a beforeclick event)? Or how can I make click events work for disabled radio buttons?


This effectively stops the click from getting through to the unwanted radio buttons:

http://jsfiddle.net/df9ye/5/

$('#r3, #r4').mousedown(function(e) {
    e.stopPropagation();
    alert($(this).attr('id'));
});


I would simply add a list with previously pressed radiobuttons. So you when you get to the one to show the alert for you simply show the alert -> pop from the last in the list/variable and simply set that to checked.

From the top of my head:

var lastClick;
$("input[@name='r']".changed(function () {

   if("input[@id='r3']][checked=true]"){
        window.alert("r3 was pressed"); 
        $("#r3").checked = false;
        $(lastClick).checked = true;
    }else{
        lastClick ="#" + GetTheOneSelected;
    }                
});

Dont remember all the syntax but I hope you get the picture.

0

精彩评论

暂无评论...
验证码 换一张
取 消