![](/img/trans.png)
[英]innerText value is undefined when returned from promise despite being there on the console
[英]Value from checkboxes not being returned
我有幾個復選框,我試圖循環並獲取其值。 但是,我的 JS function 在選中一個框時沒有返回值。 我對 JS 很陌生,非常感謝任何幫助:代碼如下所示:
<body>
<script src="racquetObjects.js"></script>
<div class="mainContainer">
<div class="selectors">
<form action="">
<div class="brandName">
<input type="checkbox" id="babolat" value="Babolat" />
<label for="babolat">Babolat</label>
<input type="checkbox" id="wilson" value="Wilson" />
<label for="wilson">Wilson</label>
</div>
<div class="characteristics">
<input type="checkbox" id="power" value="Power" />
<label for="power">Power</label>
<input type="checkbox" id="control" value="" />
<label for="control">Control</label>
<input type="checkbox" id="popular" value="" />
<label for="popular">Popular</label>
</div>
<input type="submit" value="Find" id="search" />
</form>
</div>
<div class="racquetContainer"></div>
<div class="bench"></div>
</div>
<script src="racquetFinder.js"></script>
</body>
const brandNameCB = document.querySelector(".brandName").children;
function isChecked() {
for (var i = 0; i < brandNameCB.length; i++) {
if (
brandNameCB[i].tagName === "INPUT" &&
brandNameCB[i].type === "checkbox"
) {
if (brandNameCB[i].checked) {
console.log(brandNameCB[i].value + " is Selected!);
}
}
}
}
您需要使用某些事件觸發 isChecked 。 Onchange 輸入將是一個不錯的選擇。
<input type="checkbox" id="wilson" value="Wilson" onchange="isChecked()"/>
將此屬性添加到要觸發事件的復選框。
此外,您的代碼現在僅適用於品牌名稱,因為您使用的是品牌名稱CB。 不是為了特征。
看起來你想添加一個事件監聽器:
document.querySelectorAll(".brandName input[type=checkbox]").forEach(el => {
el.addEventListener('click', (e) => {
console.log(e.target.checked);
});
});
我認為您錯過了 getAttribute() function cause.type and.checked 不在規范中。 嘗試這個:
function isChecked() { for (var i = 0; i < brandNameCB.length; i++) { if ( brandNameCB[i].tagName === "INPUT" && brandNameCB[i].getAttribute(type) === "checkbox" ) { if (brandNameCB[i].getAttribute(checked)) { console.log(brandNameCB[i].getAttribute(value) + " is Selected;); } } } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.