[英]Can I use Javascript to detect whether a checkbox has been checked?
我正在嘗試使用Javascript檢測復選框是否已選中。 我的計划是允許用戶選中復選框,以將字母標記為已打印,然后使用Ajax更新數據庫。
這是我正在使用的代碼。
<label for="printed">Printed</label>
<input type="checkbox" name="8200" id="8200" value="P" onclick="checked(this.id);" />
<script type="text/javascript">
function checked(id) {
var remember = document.getElementById(id);
if (remember.checked){
alert("checked");
}else{
alert("You didn't check it!");
}
}
</script>
我得到的只是一個錯誤消息: Uncaught TypeError: boolean is not a function from Google Chrome and checked is not a function from Firefox.
您應該使用與javascript方法不同的名稱,因為輸入的布爾值選中字段只會隱藏您已定義的字段...
您需要更改javascript方法的名稱。
HTML:
<label for="printed">Printed</label>
<input type="checkbox" name="8200" id="8200" value="P" onclick="isChecked(this.id);" />
JS:
function isChecked(id) {
var remember = document.getElementById(id);
if (remember.checked){
alert("checked");
}else{
alert("You didn't check it!");
}
}
看看這個JSFiddle: http : //jsfiddle.net/6dx6A/39/
只需簡單地更改您使用的函數名稱為“ checked(this.id)”即可。 我試過checked1(this.id)。 有效
您可以按以下方式更改函數名稱以獲得答案。 對我有用
function IsChecked(id)
{
var remember = document.getElementById(id);
if (remember.checked){
alert("checked");
}else{
alert("You didn't check it!");
}
}
由於您有一個我不滿意的其他jQuery解決方案,因此,我將為您提供jQuery解決方案:
<input type="checkbox" name="8200" id="theid" value="P" />
// 8200 isn't a valid id in HTML4, it can't start with a number
$('#theid').change(function(){
if (this.checked)
alert('checked');
else
alert('unchecked');
});
這是您在JQuery解決方案中所擁有的,將適用於頁面上的每個復選框(將類添加到選擇器中,以便僅將其應用於某些復選框)
$(function(){
var remember;
$('input:checkbox').click(function(){
remember = $(this).attr('id');
if($(this).is(':checked')){
// Checkbox is checked
} else {
// Checkbox is NOT checked
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.