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 :(
<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/
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.
The ' event.target
' will be the element you clicked.
This is how you should define this eventhandler:
onclick="testCheckbox"
Now you can write your script like this:
function testCheckbox(event) { if (event.target.checked == true) { document.getElementById("oTxtbox").value=1; } else { document.getElementById("oTxtbox").value=""; } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.