jQuery 获取在用户选择新按钮之前选择的单选按钮的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11052702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:07:38  来源:igfitidea点击:

Get the value of the radio button that was selected before the user selects a new one

jqueryradio-button

提问by David Gard

If I have 3 radio buttons, is there a way through jQuery of finding out the value of the one that was selected before the user clicks a new one?

如果我有 3 个单选按钮,有没有办法通过 jQuery 找出在用户单击新按钮之前选择的那个按钮的值?

<div id="radio-group">
    <input type="radio" id="radio-1" name="radios" value="1" checked="true" />
    <input type="radio" id="radio-2" name="radios" value="2" />
    <input type="radio" id="radio-3" name="radios" value="3" />
</div>

In the example avove, if the user clicks on radio-3, I need a way to get 1, so that I can carry out some formattion to it. Thanks.

在示例 avove 中,如果用户单击radio-3,我需要一种方法来获取1,以便我可以对其进行一些格式化。谢谢。

采纳答案by Ville

I would save the pressed values to an array and edit hidden value with that.

我会将按下的值保存到一个数组中并用它编辑隐藏值。

http://jsfiddle.net/BQDdJ/6/

http://jsfiddle.net/BQDdJ/6/

HTML

HTML

<div id="radio-group">
    <input type="radio" id="radio-1" name="radios" value="1" checked="true" />
    <input type="radio" id="radio-2" name="radios" value="2" />
    <input type="radio" id="radio-3" name="radios" value="3" />
    <input type="hidden" id="radio-previous" name="radio-previous" />
</div>?

JavaScript

JavaScript

$(document).ready(function(){
    var clicks = new Array();
    clicks[0] = 1 //this should be the default value, if there is one

    $('input[name$="radios"]').change(function(){
       clicks.push($(this).val()) 
       $('#radio-previous').val(clicks[clicks.length-2])
    })
})

?

?

回答by Adil

You can use mouseupand changeevent. In mouse up you will get the value of radiobutton that is selected before selecting other radion button and change event will give the new selection of radiobutton.

您可以使用mouseupchange事件。在鼠标向上时,您将获得radio在选择其他单选按钮之前选择的按钮的值,更改事件将提供新的radio按钮选择。

Live Demo

现场演示

$('input[name=radios]').mouseup(function(){
    alert("Before change "+$('input[name=radios]:checked').val());
}).change(function(){
    alert("After change "+$('input[name=radios]:checked').val());
})?;

回答by Carlos Arturo Alaniz

I had the same issue when trying to make a budget calculator with options, I solved it using a a var to hold the last value;

我在尝试制作带有选项的预算计算器时遇到了同样的问题,我使用 aa var 来保存最后一个值来解决它;

            var before = -1;
            $('input:checkbox, input:radio').click(function() {
                // +(str) =  number(str)
                var value = +$(this).val();
                if ($(this).is(":checkbox")) {
                    if ($(this).is(":checked")) {
                        total += value;
                    } else {
                        total -= value;
                    }
                }
                else {
                    if (before < 0) {
                        total += value;
                        before = value;
                    } else {
                        total -= before;
                        total += value;
                        before = value;
                    }
                }
                $("#sub-total").text(total * hourly_rate);
                if ($(this).is("[data-toggle]")) {
                    $("#" + $(this).attr("data-toggle")).slideToggle("fast");
                }
            });

回答by Scaramouche

"It's been a while" would be an euphemism but in case someone stumbles upon this issue:

“已经有一段时间了”是一种委婉说法,但万一有人偶然发现这个问题:

Adilpointed me in the right direction, however mouseuponly works for mouse-triggered events (duh), so I tried with focusand, since it also happensbefore changeevent, it works with, both, mouse and keyboard inputs (like when you change the radios status using the taband arrowkeys). So to gain access to the previously selected/checked item before the user interaction you use focusand to get the current item you use your good old change:

Adil 为我指明了正确的方向,但mouseup仅适用于鼠标触发的事件(废话),所以我尝试使用focus并且,因为它也发生change事件之前,因此它适用于鼠标和键盘输入(例如当您更改收音机时)状态使用选项卡箭头键)。因此,要在您使用的用户交互之前访问先前选择/选中的项目focus并获取当前项目,请使用旧的change

//html
    <input type="radio" id="radio-1" name="radios" value="1" />
    <input type="radio" id="radio-2" name="radios" value="2" />

//js
    //if currently checked item is radio-1
    $('[name=radios]').on('focus', function() {
        console.log($('[name="radios"]:checked').val()); //outputs 1
    });
    $('[name=radios]').change(function() {
        console.log($('[name="radios"]:checked').val()); //outputs 2
    });

回答by Guito

Just to complete #Adil's answer, if you have radios with text, if the user clicks the text, the previousRadio doesn't get updated. You can use the following:

只是为了完成#Adil 的回答,如果你有带文本的收音机,如果用户点击文本,previousRadio 不会更新。您可以使用以下内容:

<label>
   <input type="radio" name="radioName">
   text
</label>

And js:

和js:

var $previousRadio;
var $inputs = $('input[name=radioName]');
$inputs.parents("label").mouseup(function () {
    $previousRadio = $inputs.filter(':checked');
});
$inputs.change(function () {
    alert($previousRadio.val());
});