【问题标题】:Display message when checkbox is checked in Javascript在Javascript中选中复选框时显示消息
【发布时间】:2018-03-16 03:24:05
【问题描述】:
我知道它应该很简单,但我找不到方法去做,我有一种感觉很简单,但我被卡住了。每次选中复选框时,我都会尝试显示一条消息。我有下面的代码,但我只能显示第一个复选框的消息。我只是从 Javascript 开始。
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text" style="display:none">Checkbox is CHECKED!</p>
Checkbox2: <input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text" style="display:none">Second checkbox is checked</p>
Checkbox3: <input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text" style="display:none">Third checkbox is checked</p>
</body>
</html>
【问题讨论】:
标签:
javascript
jquery
html
checkbox
【解决方案1】:
id 必须是唯一的,您可以将checkbox 和p 的id 作为参数传递,功能如下,
function myFunction(id,pid) {
var checkBox = document.getElementById(id);
var text = document.getElementById(pid);
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
Checkbox: <input type="checkbox" id="myCheck1" onclick="myFunction(this.id,'text1')">
<p id="text1" style="display:none">Checkbox is CHECKED!</p>
Checkbox2: <input type="checkbox" id="myCheck2" onclick="myFunction(this.id,'text2')">
<p id="text2" style="display:none">Second checkbox is checked</p>
Checkbox3: <input type="checkbox" id="myCheck3" onclick="myFunction(this.id,'text3')">
<p id="text3" style="display:none">Third checkbox is checked</p>
</body>
</html>
【解决方案2】:
不会继续讨论why #IDs need to be unique 的重要性以及它如何阻碍复选框的预期行为。有 2 个演示:
Demo 1 使用 IMO 的 JavaScript 来完成一项简单的任务。
-
对于事件处理,尽量避免使用on-event attribute event handlers:
<div onclick="func();"></div>
改用addEventListener(),点击链接了解详情。
Event Delegation 在 Demo 1 中使用,因此只有添加的 <form> 元素用作 eventListener 而不是多个复选框。
-
引用表单控件(例如input、textarea 等)的另一种方法是使用HTMLFormControlsCollection API。将输入包装到一个实际的<form> 标签中,并给它们#id 和/或[name] 属性,我们可以使用简单而简短的语法。在这个演示中,它确实不是必需的,但这里有一个传统方式与 事件委托/HTMLFCC 的示例:
正常方式:
var chxs = document.querySelectorAll('[type=checkbox]');
for (let i = 0; i < chxs.length; i++) {
chxs[i].addEventListener('change', message);
}
事件委托/HTMLFormControlsCollection
var form = document.forms.formID;
form.addEventListener('change', message);
Demo 2 仅使用 CSS。
Demos 中评论的详细信息
演示1
// Reference the form - see HTMLFormControlsCollection
var chxGrp = document.forms.checkGroup;
/* Register the change event to form.
|| Call message() function when a change event happens on or
|| within the form.
|| A change event occurs when the user enters data (*input*)
|| within a form control like an input (*focus*) then clicks onto
|| another (*unfocus*).
|| change event is different than most of the events because it
|| involves multple steps from the user, but it is very effective
|| for form controls.
*/
chxGrp.addEventListener('change', message);
/* The Event Object is passed through, you might've seen it as
|| "e" or "evt". How it's labelled doesn't matter because Event
|| Object is always available when you deal with the DOM.
*/
function message(event) {
// if the node clicked is a checkbox see if it's...
if (event.target.type === 'checkbox') {
// ... checked then...
if (event.target.checked) {
// ...find the node that follows it (i.e. <b>)...
event.target.nextElementSibling.className = "message";
} else {
/* Otherwise remove any class on it. (there's a more modern
|| method: classList that can be used instead)
*/
event.target.nextElementSibling.className = "";
}
}
return false;
}
b {
display: none
}
label {
display: table
}
[type=checkbox] {
display: table-cell;
}
.message {
display: table-cell;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- Wrapped the checkboxes with a <form> giving us opportunities:
HTMLFormControlsCollection API for specialized referencing and
Event Delegation allowing us to use a single eventListener for an
unlimited amount of event.targets (clicked, changed, inputed,
etc. buttons, links, etc.)-->
<form id='checkGroup'>
<p>Display some text when the checkbox is checked: </p>
<label>Checkbox 1: <input type="checkbox">
<b>Checkbox is CHECKED!</b>
</label><br>
<label>Checkbox 2: <input type="checkbox">
<b>Second checkbox is checked</b>
</label><br>
<label>Checkbox 3: <input type="checkbox">
<b>Third checkbox is checked</b>
</label><br>
</form>
</body>
</html>
演示 2 - 仅 CSS
/* Default state of message tag */
b {
display: none
}
/* Using label as a container that acts like a table */
label {
display: table
}
/* Checkboxes are normally set as a component that sits inline
with their siblings. Acting as a table-cell does that and has
additional advantages as well.
When the checkbox is :checked...
The adjacent sibling + <b> behaves as a table-cell as well,
thereby being shown/hidden by the corresponding checkbox being
toggled.
*/
[type=checkbox],
[type=checkbox]:checked + b {
display: table-cell;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- Layout has been slightly re-arranged to take advantage of
styling combonations and tag behavior -->
<p>Display some text when the checkbox is checked: </p>
<label>Checkbox 1: <input type="checkbox">
<b>Checkbox is CHECKED!</b>
</label><br>
<label>Checkbox 2: <input type="checkbox">
<b>Second checkbox is checked</b>
</label><br>
<label>Checkbox 3: <input type="checkbox">
<b>Third checkbox is checked</b>
</label><br>
</body>
</html>
【解决方案3】:
您有多个具有相同 ID 的元素。尝试将两个 ID 更改为末尾有一个数字(myCheck 1 或 myCheck2),或者将其完全更改为其他内容。这是我的建议:
function myFunction(idCheck, idText) {
var checkBox = document.getElementById(idCheck);
var text = document.getElementById(idText);
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction('myCheck', 'text')">
<p id="text" style="display:none">Checkbox is CHECKED!</p>
Checkbox2: <input type="checkbox" id="myCheck1" onclick="myFunction('myCheck1', 'text1')">
<p id="text1" style="display:none">Second checkbox is checked</p>
Checkbox3: <input type="checkbox" id="myCheck2" onclick="myFunction('myCheck2', 'text2')">
<p id="text2" style="display:none">Third checkbox is checked</p>
</body>
</html>
【解决方案4】:
首先你需要有一个带有 uniq id 的输入类型复选框。
<input type="checkbox" id="uniq_id" />
然后在脚本中调用你的函数
$("#uniq_id").click( function(){
if( $(this).is(':checked') ){
//call your function here
myFunction(this);
}
});
【解决方案5】:
id 必须是唯一的。使用this.id 将id 传递给onclick 处理程序
function myFunction(id) {
var checkBox = document.getElementById(id);
var text = document.getElementById("text");
if (checkBox.checked === true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<p>Display some text when the checkbox is checked:</p>
Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction(this.id)">
<p id="text" style="display:none">Checkbox is CHECKED!</p>
Checkbox2: <input type="checkbox" id="myCheck2" onclick="myFunction(this.id)">
<p id="text" style="display:none">Second checkbox is checked</p>
Checkbox3: <input type="checkbox" id="myCheck3" onclick="myFunction(this.id)">
<p id="text" style="display:none">Third checkbox is checked</p>
【解决方案6】:
好吧,由于 id 是唯一标识符,因此您的函数总是选择第一个复选框。
document.getElementById("myCheck");
您需要将其修改为 smth.像这样
<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
Checkbox:
<input type="checkbox" id="check_1" onclick="myFunction(event)">
<p id="text_check_1" style="display:none">Checkbox is CHECKED!</p>
Checkbox2:
<input type="checkbox" id="check_2" onclick="myFunction(event)">
<p id="text_check_2" style="display:none">Second checkbox is checked</p>
Checkbox3:
<input type="checkbox" id="check_3" onclick="myFunction(event)">
<p id="text_check_3" style="display:none">Third checkbox is checked</p>
<script>
function myFunction(event) {
var checkBox = event.target,
id = checkBox.id,
text = document.getElementById("text_" + id);
if (checkBox.checked == true) {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
</script>
</body>
</html>
【解决方案7】:
确实,您必须使用不同的 ID,而且您不需要多个 p 元素,最后为了避免不必要的查询,您可以将单击的元素传递给函数,因为您通过 onclick 调用它属性。
function myFunction(elem) {
var checkBox = elem;
var p = document.getElementsByTagName('p')[1];
if (checkBox.checked == true){
p.innerHTML = "Checkbox <b>" + checkBox.id + "</b> is CHECKED!"
p.style.display = "block";
} else {
p.style.display = "none";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
Checkbox: <input type="checkbox" id="myCheck1" onclick="myFunction(this)">
<p class="text" style="display:none"></p>
Checkbox2: <input type="checkbox" id="myCheck2" onclick="myFunction(this)">
Checkbox3: <input type="checkbox" id="myCheck3" onclick="myFunction(this)">
</body>
</html>
嗨
【解决方案8】:
您根本不需要 javascript 或 jquery - 这可以单独使用 CSS 来实现 - 使用直接兄弟选择器和 :checked 伪选择器,您可以在下一个 p 上设置 display 或 visibility 属性。
您确实有多个 id,因此需要更正 - 但 CSS 是您在选中复选框后切换下一个 p 所需的全部内容。
p{display: none}
input[type="checkbox"]:checked + p {display: block}
<p>Display some text when the checkbox is checked:</p>
Checkbox: <input type="checkbox" id="myCheck1">
<p>First Checkbox is CHECKED!</p>
Checkbox2: <input type="checkbox" id="myCheck2">
<p>Second checkbox is checked</p>
Checkbox3: <input type="checkbox" id="myCheck2">
<p>Third checkbox is checked</p>