我的任务是使用JavaScript启用单击(单击)复选框的时间,并在单击(关闭)时禁用它。 但是,代码仍然无效,无论是否单击复选框都不会执行任何操作。
</head>
<body>
<div id="container">
<h2> Order Information </h2>
<div class="entry">
Select color:
<select name="color">
<option selected="selected">White</option>
<option>Black</option>
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select> <br><br>
Select shirt size:
<select name="sizeandprice">
<option>Small - $9.99</option>
<option>Medium - $10.99</option>
<option selected="selected">Large - $11.99</option>
<option>X-Large - $13.99</option>
</select><br><br>
Is this a gift? <input type="checkbox" name="gift"> <br><br>
Write your gift message here: <br>
<textarea disabled rows="5" cols="50" name="message">Type your message here.
</textarea>
</div>
</div>
</body>
</html>
这是Javascript代码:
function enable(x) {
x = document.getElementbyId("gift");
x.checked
if(x == true) {
var textarea = document.getElementbyId("message");
textarea.disabled = false;
}
else {
var textarea = document.getElementbyId("message");
textarea.disabled = true;
}
}
答案 0 :(得分:1)
问题是你的函数永远不会被调用。您需要绑定调用click
的{{1}}事件回调函数。您还需要一些其他代码调整 - 请参阅内联注释:
enable
&#13;
// Get reference to checkbox and textarea just once, not over and over
// Also, you were using .getElementById(), but your elements weren't
// given id's, they have names
var chk = document.querySelector("input[name=gift]"); // id is not "gift", name is
var textarea = document.querySelector("textarea[name=message"); // id is not "message", name is
// Set up click event handler:
chk.addEventListener("click", enable);
function enable() {
// Just base the disabled of the textarea on the opposite
// of the checkbox's checked state
textarea.disabled = !this.checked;
}
&#13;
答案 1 :(得分:1)
document.getElementById('giftCheckbox').addEventListener( 'click', function(){
var textArea = document.getElementById('messageTxtArea')
textArea.disabled = !textArea.disabled
});
&#13;
<body>
<div id="container">
<h2> Order Information </h2>
<div class="entry">
Select color:
<select name="color">
<option selected="selected">White</option>
<option>Black</option>
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select> <br><br>
Select shirt size:
<select name="sizeandprice">
<option>Small - $9.99</option>
<option>Medium - $10.99</option>
<option selected="selected">Large - $11.99</option>
<option>X-Large - $13.99</option>
</select><br><br>
Is this a gift? <input type="checkbox" id="giftCheckbox" name="gift"> <br><br>
Write your gift message here: <br>
<textarea disabled rows="5" cols="50" id="messageTxtArea" name="message">Type your message here.
</textarea>
</div>
</div>
</body>
&#13;
我在你的复选框和textarea中添加了id。我使用 .addEventListener()在您的复选框点击事件上注册回调,该事件启用/禁用textarea元素。
答案 2 :(得分:-1)
您的输入类型元素已被赋予属性name="gift"
,并且您正在搜索包含id="gift"
的元素。您可以将属性从name更改为id或使用document.getElementsByName("gift")
。请参阅document.document.getElementsByName