[英]check box checked javascript
I am trying to set a value in a text box based on whether the checkbox is checked or not The function is attached to onclick of the checkbox This simple thing is not working :(我试图根据复选框是否被选中在文本框中设置一个值该功能附加到复选框的onclick 这个简单的事情不起作用:(
<div>
MyCheckbox
<input type="checkbox" id="Check1" name="FirstCkName"
onclick="testCheckbox(Check1,TextBx1)" />
</div><br>
<div>
CheckBx Text Box
<input id="TextBx1" name="CheckBxName" type="text" />
</div><br>
<script>
function testCheckbox(oCheckbox,oTxtbox)
{
if (oCheckbox.checked == true)
{
document.getElementById("oTxtbox").value=1;
}
else
{
document.getElementById("oTxtbox").value="";
}
}
</script>
Link to JSfiddle https://jsfiddle.net/JS_learner/2750639m/30/链接到 JSfiddle https://jsfiddle.net/JS_learner/2750639m/30/
Do something like.做类似的事情。
var checkBox = document.getElementById("Check1"); checkBox.addEventListener("click", function(e) { if (e.target.checked) { document.getElementById("TextBx1").value = 1; } else { document.getElementById("TextBx1").value = ""; } });
<div> MyCheckbox <input type="checkbox" id="Check1" name="FirstCkName" /> </div><br> <div> CheckBx Text Box <input id="TextBx1" name="CheckBxName" type="text" /> </div>
The problem is this line:问题是这一行:
onclick="testCheckbox(Check1,TextBx1)"
Here you're inventing your own parameters.在这里,您正在发明自己的参数。 That won't Work.
那行不通。 The 'click' event is a predefined
Mousevent
, which will give an 'event'
argument. 'click' 事件是一个预定义的
Mousevent
,它将给出一个'event'
参数。
The ' event.target
' will be the element you clicked. '
event.target
' 将是您单击的元素。
This is how you should define this eventhandler:这是您应该如何定义此事件处理程序:
onclick="testCheckbox"
Now you can write your script like this:现在您可以像这样编写脚本:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.