正在确定检查的最后一个单选按钮

Determining the last radio button checked

本文关键字:最后一个 单选按钮 检查      更新时间:2023-09-26

假设一组4个无线电盒子,选中第一个。然后用户单击第三个单选框。有没有办法知道第一台收音机是最后一台检查的?

如果绑定到mousedown事件而不是click,则当事件侦听器运行时,选中的无线电不会发生更改:

<fieldset id="radios">
    <input type="radio" name="rad" value="1"> option 1<br>
    <input type="radio" name="rad" value="2"> option 2<br>
    <input type="radio" name="rad" value="3"> option 3<br>
</fieldset>
var radios = document.getElementById('radios');
radios.addEventListener('mousedown', function(e) {
    var clicked = e.target;
    var current = document.querySelector('input[name=rad]:checked');
});

http://jsfiddle.net/ej6WD/

注意:此解决方案是IE8+,请参阅http://caniuse.com/#search=queryselector

1(声明全局变量

var currentlySelected = null;

2( 将处理程序附加到所有单选按钮的单击事件。

function radioButtonOnClickEvent() {
    if (currentlySelected === null) { 
        // nothing has been selected yet
        currentlySelected = radioBoxThatWasJustClicked;
    } else if (currentlySelected === theThirdRadioButton) {
         //your logic here
         currentlySelected = radioBoxThatWasJustClicked;
    }
}

是的,有一种方法可以做到这一点。我已经添加了你的代码和完成的脚本,以获得最后一个选择单选按钮。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Test webservices</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    <script>
        $(document).ready(function () {
            $('input[name="rad"]').click(function (e) {
                if($(this).siblings('input[name="rad"]').hasClass('lastSelected'))
                {
                    var lastSelectedButton = $('.lastSelected').val();
                    $(this).siblings('input[name="rad"]').removeClass('lastSelected');
                    $(this).addClass('lastSelected');
                }
                else
                    $(this).addClass('lastSelected');
            });
        });
    </script>
</head>
<body>
    <form action='xyz.php' method='get'>
        <input type="radio" name="rad" value="1"> option 1<br>
        <input type="radio" name="rad" value="2"> option 2<br>
        <input type="radio" name="rad" value="3"> option 3<br>
        <input type='submit' value='Go' id='submit' >
    </form>
</body>
</html>

这是你问题的完美答案。你可以试着用这个脚本的复制粘贴来实现它。