Javascript 复选框 onChange
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6358673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript checkbox onChange
提问by bikey77
I have a checkbox in a form and I'd like it to work according to following scenario:
我在表单中有一个复选框,我希望它根据以下情况工作:
- if someone checks it, the value of a textfield (
totalCost
) should be set to10
. - then, if I go back and uncheck it, a function
calculate()
sets the value oftotalCost
according to other parameters in the form.
- 如果有人检查它,则文本字段 (
totalCost
)的值应设置为10
。 - 然后,如果我返回并取消选中它,一个函数会根据表单中的其他参数
calculate()
设置 的值totalCost
。
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
所以基本上,我需要的部分是,当我选中复选框时,我会做一件事,当我取消选中它时,我会做另一件事。
回答by Senad Me?kin
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
回答by Vic
Pure javascript:
纯javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.target.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
回答by Liangliang Zheng
If you are using jQuery.. then I can suggest the following: NOTE: I made some assumption here
如果您正在使用 jQuery .. 那么我可以提出以下建议: 注意:我在这里做了一些假设
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
回答by SergeS
Use an onclick event, because every click on a checkbox actually changes it.
使用 onclick 事件,因为每次单击复选框实际上都会改变它。
回答by Eugene
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId
.
以下解决方案使用了 jquery。假设您有一个 ID 为 的复选框checkboxId
。
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
回答by Bart
Reference the checkbox by it's id and not with the # Assign the function to the onclick attribute rather than using the change attribute
通过它的 id 而不是使用 # 将函数分配给 onclick 属性而不是使用更改属性来引用复选框
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
回答by Ali Kleit
HTML:
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
JS:
function handleChange(e) {
const {checked} = e.target;
}
回答by Bruce Tong
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
我知道这似乎是菜鸟的答案,但我把它放在这里是为了将来可以帮助其他人。
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
假设您正在构建一个带有 foreach 循环的表。同时在末尾添加复选框。
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
您在表格下方放置一个带有隐藏输入的按钮:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
您可以像这样编写脚本:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.
您的复选框的 id 将作为结果变量中的字符串“1,2”提交。然后,您可以根据需要在控制器级别将其分解。
回答by 0x1ad2
Javascript
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
回答by Kamil Kie?czewski
try
尝试
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />