我在寻找一个广义解。

考虑具有相同名称的2个无线电类型输入。当提交时,被选中的值决定随表单一起发送的值:

<input type="radio" name="myRadios" onchange="handleChange1();" value="1" />
<input type="radio" name="myRadios" onchange="handleChange2();" value="2" />

取消选择单选按钮时,更改事件不会触发。因此,如果值="1"的无线电已经被选中,而用户选择了第二个,则handleChange1()不会运行。这就出现了一个问题(至少对我来说),因为我无法捕捉到这种去选择。

我想要的是一个变通的onChange事件的复选框组值,或者,一个onCheck事件,不仅检测单选按钮是选中的,而且当它是未选中的。

我相信你们中的一些人以前遇到过这个问题。有什么变通办法(或者理想情况下,什么是处理这个问题的正确方法)?我只是想捕捉变化事件,访问以前检查的收音机以及新检查的收音机。

注: onClick似乎是一个更好的(跨浏览器的)事件来指示选中单选按钮,但它仍然不能解决未选中的问题。

我认为这是有意义的,为什么onChange复选框类型在这样的情况下工作,因为它改变了它提交的值,当你勾选或取消勾选它。我希望单选按钮表现得更像一个SELECT元素的onChange,但你能做什么…


当前回答

博士Tl;

'focusout'在'change'事件之前被分派-示例:

const radioName = 'radio';

// Add radios
document.body.innerHTML = `
<style>
input + label {
  margin-left: 1rem;
}
</style>
<form action="#" name="example-form">
  <fieldset>
    ${Array(5).fill(null, 0, 5).map((_, i) => {
        const offsetId = i + 1;
        const id = `radio-${offsetId}`;
        return `<label for="${id}">Radio ${offsetId}</label>
        <input type="radio" name="${radioName}" id="${id}" value="${offsetId}" />`;
      }).join('\n')}
  </fieldset>
</form>
`;

const {log} = console,

    form = document.forms['example-form']; 

form.addEventListener('submit', e => e.preventDefault());

form.addEventListener('change', e => {
    const {target} = e;
    if (target.matches(`[type="radio"][name="${radioName}"]`)) {
        log(`[${e.type}]: "${target.id}" selected;  Value: ${target.value}`);
    }
});

form.addEventListener('focusout', e => {
    const {target} = e,

        soonToBePrevValue = target && target.form ? 
            target.form.elements[radioName].value : null;
    
    if (!target.matches(`[type="radio"][name="${radioName}"]`) || !soonToBePrevValue) {
        return;
    }

    // value, for '[name="radio"]', contained in form, will change after 'focusout' event
    // has completed it's bubbling stage.
    log(`[${e.type}]: previously selected radio value: ` + 
        `${soonToBePrevValue}`);
        
    // log("Soon to be \"previous\" radio: ", target);
});

斯菲德尔

其他回答

除了存储之前的状态,我不认为还有其他方法。 下面是使用jQuery的解决方案

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<script type="text/javascript">
    var lastSelected;
    $(function () {
        //if you have any radio selected by default
        lastSelected = $('[name="myRadios"]:checked').val();
    });
    $(document).on('click', '[name="myRadios"]', function () {
        if (lastSelected != $(this).val() && typeof lastSelected != "undefined") {
            alert("radio box with value " + $('[name="myRadios"][value="' + lastSelected + '"]').val() + " was deselected");
        }
        lastSelected = $(this).val();
    });
</script>

<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
<input type="radio" name="myRadios" value="4" />
<input type="radio" name="myRadios" value="5" />

在考虑了一会儿之后,我决定去掉变量并添加/删除类。这是我得到的:http://jsfiddle.net/BeQh3/2/

出于某种原因,最好的答案对我来说并不适用。

我通过实践改进了最佳答案

    var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');

原最佳答案用法:

      var rad = document.myForm.myRadios;

其他人保持不变,最后对我有用。

var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
                              console.log('overlayType_radio', overlayType_radio)

                              var prev = null;
                              for (var i = 0; i < overlayType_radio.length; i++) {
                                  overlayType_radio[i].addEventListener('change', function() {
                                      (prev) ? console.log('radio prev value',prev.value): null;
                                      if (this !== prev) {
                                          prev = this;
                                      }
                                      console.log('radio now value ', this.value)
                                  });
                              }

html是:

<div id='overlay-div'>
                        <fieldset>
                                <legend> Overlay Type </legend>
                                
                                <p>
                                    <label>
                                      <input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
                                      <span>Image</span> 
                                    </label>
                                </p>

                                <p>
                                  <label>
                                    <input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' disabled/>
                                    <span> Tiled Image</span>   
                                </p>

                                <p>
                                  <label>
                                    <input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio'  disabled/>
                                    <span> Coordinated Tile</span>  
                                </p>

                                <p>
                                  <label>
                                    <input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
                                    <span> None </span>            
                                  </p>

                                  
                          </fieldset>
                       </div>

var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]'); console.log('overlayType_radio', overlayType_radio) var prev = null; for (var i = 0; i < overlayType_radio.length; i++) { overlayType_radio[i].addEventListener('change', function() { (prev) ? console.log('radio prev value',prev.value): null; if (this !== prev) { prev = this; } console.log('radio now value ', this.value) }); } <div id='overlay-div'> <fieldset> <legend> Overlay Type </legend> <p> <label> <input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/> <span>Image</span> </label> </p> <p> <label> <input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' /> <span> Tiled Image</span> </p> <p> <label> <input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' /> <span> Coordinated Tile</span> </p> <p> <label> <input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/> <span> None </span> </p> </fieldset> </div>

点击这里

https://jsfiddle.net/hoogw/jetmkn02/1/

我想做两点改变:

<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />

使用onclick处理程序而不是onchange -您正在更改无线电输入的“已检查状态”,而不是值,因此不会发生更改事件。 使用单个函数,并将其作为参数传递,这将便于检查当前选择的值。

ETA:除了handleClick()函数,您还可以在页面作用域变量中跟踪收音机的原始/旧值。那就是:

var currentValue = 0;
function handleClick(myRadio) {
    alert('Old value: ' + currentValue);
    alert('New value: ' + myRadio.value);
    currentValue = myRadio.value;
}

var currentValue = 0; 函数handleClick(myRadio) { alert('旧值:' + currentValue); alert('新值:' + myRadio.value); currentValue = myRadio.value; } <input type="radio" name=" my" onclick="handleClick(this);" value="1" /> . <input type="radio" name=" my" onclick="handleClick(this);" value="2" /> .

博士Tl;

'focusout'在'change'事件之前被分派-示例:

const radioName = 'radio';

// Add radios
document.body.innerHTML = `
<style>
input + label {
  margin-left: 1rem;
}
</style>
<form action="#" name="example-form">
  <fieldset>
    ${Array(5).fill(null, 0, 5).map((_, i) => {
        const offsetId = i + 1;
        const id = `radio-${offsetId}`;
        return `<label for="${id}">Radio ${offsetId}</label>
        <input type="radio" name="${radioName}" id="${id}" value="${offsetId}" />`;
      }).join('\n')}
  </fieldset>
</form>
`;

const {log} = console,

    form = document.forms['example-form']; 

form.addEventListener('submit', e => e.preventDefault());

form.addEventListener('change', e => {
    const {target} = e;
    if (target.matches(`[type="radio"][name="${radioName}"]`)) {
        log(`[${e.type}]: "${target.id}" selected;  Value: ${target.value}`);
    }
});

form.addEventListener('focusout', e => {
    const {target} = e,

        soonToBePrevValue = target && target.form ? 
            target.form.elements[radioName].value : null;
    
    if (!target.matches(`[type="radio"][name="${radioName}"]`) || !soonToBePrevValue) {
        return;
    }

    // value, for '[name="radio"]', contained in form, will change after 'focusout' event
    // has completed it's bubbling stage.
    log(`[${e.type}]: previously selected radio value: ` + 
        `${soonToBePrevValue}`);
        
    // log("Soon to be \"previous\" radio: ", target);
});

斯菲德尔

这对我很有用

<input ID="TIPO_INST-0" Name="TIPO_INST" Type="Radio" value="UNAM" onchange="convenio_unam();">UNAM

<script type="text/javascript">
            function convenio_unam(){
                if(this.document.getElementById('TIPO_INST-0').checked){
                    $("#convenio_unam").hide();
                }else{
                    $("#convenio_unam").show(); 
                }                               
            }
</script>