[英]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
。 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.