【问题标题】:Check a checkbox in an html page选中 html 页面中的复选框
【发布时间】:2016-07-03 18:44:12
【问题描述】:

下午好,

我正在尝试使用脚本在我的 html 页面中勾选一个复选框。

不幸的是,我收到以下错误消息:

SCRIPT5007:无法设置未定义或空引用的属性“已检查” 文件:ajax3,行:37,列:5

你知道我的代码出了什么问题吗?

非常感谢,祝您周日愉快。

劳伦特

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo for Ajax Auto Refresh</title>
<link rel="stylesheet" type="text/css" href="css/mystyle_day.css" />
<script src="jquery-2.1.3.min.js"></script>
<script>
    /* AJAX request to checker */
    function check(){
        $.ajax({
            type: 'POST',
            url: 'checker.php',
            dataType: 'json',
            data: {
                counter:$('#message-list').data('counter')
            }
        }).done(function( response ) {
            /* update counter */
            $('#message-list').data('counter',response.current);
            /* check if with response we got a new update */
            if(response.update==true){
                $('#message-list').html(response.news);
                sayHello();
            }
        });
    }
    //Every 1 sec check if there is new update
    setInterval(check,1000);
</script>
<script>
function sayHello(){
    //console.log("Coucou");
    check();
}
function check() {
document.getElementById("chk1").checked = true;
}

function uncheck() {
document.getElementById("chk1").checked = false;
}
</script>
</head>
<body>  
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">

</div>
<input type="checkbox" name="chk1" id="chk1"> Living room<br>
<input type="checkbox" name="chk2" id="chk2"> Entrance<br>
<input type="checkbox" name="chk3" id="chk3"> Kitchen<br>
</body>
</html>

【问题讨论】:

  • 复选框没有id 属性。
  • 使用id="chk1"而不是value="chk1"
  • 非常感谢。我已相应地更正了上面的代码。

标签: javascript jquery html checkbox


【解决方案1】:

根据 nmnsud 和 gcampbell 的建议,我已将 value="chk1" 替换为 id="chk1"。现在正确的代码如下:

<input type="checkbox" name="chk1" id="chk1"> Living room<br>
<input type="checkbox" name="chk2" id="chk2"> Entrance<br>
<input type="checkbox" name="chk3" id="chk3"> Kitchen<br>

非常感谢您的贡献。最好的祝愿, 洛朗

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多