繁体   English   中英

无法读取带有value,innerHTML或checked复选框的值

[英]Can't read value of checkbox with value, innerHTML or checked

我正在做一个基础的数据库项目(因为我不熟练,只是想学习一些有趣的小知识),通过选中复选框来设置内容。 但是,当尝试选中一个框并读取它是否被选中时,它始终显示为“ null”。 我已经尝试过.value.innerHTML.checked 没有什么让我在那里。 我要做的就是用getElementById提取输入(即选中或未选中)并将其存储在var中,然后比较boolean是否为true或false以相应地在数据库中设置值。

function createSheet() {

var _container = document.getElementById("container");

checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    var valueOfId = document.getElementById("idString").checked;

错误信息:无法读取null的“已检查”属性。

编辑:感谢您的答案! 我没有显示这些行,因为我认为它们没那么重要,但是我错了,所以这里是:

function createSheet() {
var _container = document.getElementById("container");
for (var i = 0; i < 4; i++) {
    p = document.createElement("p");
    spanBird = document.createElement("span");
    checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = "myCheck" + i;
    checkbox.value = 0;
    checkbox.checked = birds.birdList[i].seen;
    spanBird.innerHTML = birds.birdList[i].name;
    p.appendChild(spanBird);
    p.appendChild(checkbox);
    container.appendChild(p);
    console.log(document.getElementById("myCheck" + i));
    document.getElementById("myCheck" + i).addEventListener("click", readBox);
    }
}

function readBox(){
getId();
theId = theId.substring(7);
console.log("idString: " + idString);
var valueOfId = document.getElementById("idString").checked;
}

HTML读取:

<section id="container">

    </section>

/编辑

有什么建议么?

几件事情:

  • 您不需要document.getElementById ,因为您已经有checkbox
  • 如其他人所述,要使用document.getElementById,您需要为复选框Element设置一个ID。 并且您还需要将元素添加到文档中。

 checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.id = "idString" console.log(checkbox.checked) document.body.appendChild(checkbox) console.log(document.getElementById("idString").checked) 

实际上,不是检查的属性为null,而是父对象为null。

我的意思是,这部分:

document.getElementById("idString")

返回null,因此它无法访问checked属性。

您需要首先使用此设置元素的ID

checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.setAttribute("id", "idString");
document.body.appendChild(checkbox)
var valueOfId = document.getElementById("idString").checked;

然后,您应该可以访问该值

为了正常工作,您首先需要为元素创建属性,如下所示。

如果没有实例化,则无法通过id调用。 试用。

的HTML

<div id="content"></div>    

JAVASCRIPT

  checkbox = document.createElement("input");
  checkbox.setAttribute("id", "idString");
  checkbox.setAttribute("type", "checkbox");
  checkbox.setAttribute("value", "0");

   var element = document.getElementById("content");
   element.appendChild(checkbox);
   var valueOfId = document.getElementById("idString").value;
   console.log(valueOfId);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM