问题
Given a set of radio buttons, like:
<input id="B_1" type="radio" name="radioName" value="1">
<input id="B_2" type="radio" name="radioName" value="2">
<input id="B_3" type="radio" name="radioName" value="3">
<input id="B_4" type="radio" name="radioName" value="4">
When one of them gets checked is it possible to know which was previously active (if there is one)?
I tried to attach the following function to the onclick
event, but it doesn't work because it returns the the presently selected radio button instead of the one that was selected before:
my_func = function() {
var checkedValue = $('input[type=radio]:checked').val();
return alert("The previously selected was: " + checkedValue);
};
I don't know if could be of any help, anyway here's the complete attempt: http://jsfiddle.net/H6h4R/
回答1:
Try this - http://jsfiddle.net/H6h4R/1/
$(":radio").on("mousedown", function() {
$("p").text( $('input[type=radio]:checked').val() );
}).on("mouseup", function() {
$('input[type=radio]').prop('checked', false);
$(this).prop('checked', true);
});
The click
event is only triggered after this exact series of events:
- The mouse button is depressed while the pointer is inside the element.
- The mouse button is released while the pointer is inside the element.
回答2:
if he uses keyboard key this can help with that
http://jsfiddle.net/DYrW3/73/
$('input[name=radios]').keydown(function(){
alert("Before change "+$('input[name=radios]:checked').val());
})
来源:https://stackoverflow.com/questions/11591335/get-previously-checked-radio-button