2

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('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?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • Possible duplicate of [preventing a user from changing the state of a radio button](http://stackoverflow.com/questions/7116217/preventing-a-user-from-changing-the-state-of-a-radio-button) – Jessica Aug 18 '16 at 02:34

2 Answers2

2

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'));
});
actionshrimp
  • 5,219
  • 3
  • 23
  • 26
  • 1
    Thanks but does this also work if it's selected by the keyboard, for example? – pimvdb May 14 '11 at 14:00
  • Hmm, unfortunately not. I've had a go at implementing a history (along the lines of Marthin's answer but using the input's data() to store the history here: http://jsfiddle.net/df9ye/56/ , but this doesnt seem to work if you update with the keyboard either. I think this is a limitation of the change event (seems to be implied in the first couple of paragraphs of http://api.jquery.com/change/) – actionshrimp May 14 '11 at 14:49
1

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.

Marthin
  • 6,413
  • 15
  • 58
  • 95