Get previously checked Radio Button

被刻印的时光 ゝ 提交于 2019-12-24 13:17:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!