如何在无线电输入上添加eventListener

时间:2016-07-14 16:40:21

标签: javascript

我有这段代码,它可以正常使用,但是在document.myform.onchange的第一时刻我尝试了document.myform.elem.onclick,而这最后一段代码并不想工作,只有当我把它放在一个表格,它为什么会发生?

<form name="myform">
            <input type="radio" name="car" value="audi">audi<br>
            <input type="radio" name="car" value="bmw">bmw
            <div id="text">some text is here</div>
 </form>

function ready() {
    var elem = document.getElementsByName("car");
    var hid = document.getElementById("text");
    var i;

    document.myform.onchange = function() {
       for (i = 0; i < elem.length; i++) {
            if (elem[0].checked == true) {
                hid.style.display = "none";
            } else {
                hid.style.display = "block";
            }
        } 
    }
}

document.addEventListener("DOMContentLoaded", ready);

3 个答案:

答案 0 :(得分:1)

嗨,你可以从这些例子中获得启发,祝你好运

<form name="myForm">
                <input type="radio" name="car"  value="1" />
                <input type="radio" name="car"  value="2" />
            </form>

    <script>
    var rad = document.myForm.car;
    var prev = null;
    for(var i = 0; i < rad.length; i++) {
        rad[i].onclick = function() {
            (prev)? console.log(prev.value):null;
            if(this !== prev) {
                prev = this;
            }
            console.log(this.value)
        };
    }
    </script>

答案 1 :(得分:1)

  • 通过change按钮(循环中)注册radio个事件而不是form
  • 检查已检查单选按钮的值
  • ,而不是处理index的{​​{1}}。

&#13;
&#13;
radio-input
&#13;
function ready() {
  var elem = document.getElementsByName("car");
  var hid = document.getElementById("text");
  for (var i = 0; i < elem.length; i++) {
    elem[i].onchange = function() {
      if (this.value === 'audi') {
        hid.style.display = "none";
      } else {
        hid.style.display = "block";
      }
    }
  }
}

document.addEventListener("DOMContentLoaded", ready);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以将change事件附加到您的广播输入中,如下所示:

function ready() {
    var radioInputs = document.myform.car,
        hid = document.getElementById("text");
    for(var i = 0; i < radioInputs.length; i++){
        radioInputs[i].onchange = function() {
            hid.style.display = radioInputs[0].checked ? 'block' : 'none';
        };
    }
}
document.addEventListener("DOMContentLoaded", ready);

&#13;
&#13;
function ready() {
	var radioInputs = document.myform.car,
        hid = document.getElementById("text");
	for(var i = 0; i < radioInputs.length; i++){
    	radioInputs[i].onchange = function() {
       		hid.style.display = radioInputs[0].checked ? 'block' : 'none';
    	};
    }
}
document.addEventListener("DOMContentLoaded", ready);
&#13;
<form name="myform">
            <input type="radio" name="car" value="audi">audi<br>
            <input type="radio" name="car" value="bmw">bmw
            <div id="text">some text is here</div>
 </form>
&#13;
&#13;
&#13;