[英]How to Get the check box checked value from list of checkboxes and call an Ajax function when check box is checked?
[英]how can i get value of multiple checked box and perform increment using value from checked box
我似乎可以通過使用帶有查詢選擇器的 id 來獲取元素。 有沒有辦法檢查是否使用 document.getelementbyId 檢查了復選框?
<script>
function checked(a,b,c){
var marked = (a+b+c)
document.write(marked);
}
function filled(){
var value1 = document.querySelector("#1:checked").value;
var value2 = document.querySelector("#2:checked").value;
var value3 = document.querySelector("#3:checked").value;
checked(value1,value2,value3);
}
<body>
<input class="chk1" id="1" type="checkbox" value="10"/>
<input class="chk2" id="2" type="checkbox" value="20"/>
<input class="chk3" id="3" type="checkbox" value="30"/>
<button name="submit" onclick="filled()" type="button" style="width: 100px; height: 100px;" >Submit</button>
</body>
您的 ID 無效。 即使它們是(例如,如果您將它們更改為以字母開頭),如果未選中復選框,則querySelector
將返回null
(因此無法訪問.value
)。
刪除 ID 並改用querySelectorAll
。 為了使事情簡潔,我會給他們一個 class 然后:checked
偽選擇器與 class 結合將 select 所有復選框。
如果可能的話,您還應該真正避免使用內聯處理程序,它們現在有太多問題值得使用。
document.querySelector('button').addEventListener('click', () => { const checkedBoxes = document.querySelectorAll('.chk:checked'); const sum = [...checkedBoxes].reduce((a, b) => a + Number(b.value), 0); console.log(sum); });
button { width: 100px; height: 100px; }
<input class="chk" type="checkbox" value="10"> <input class="chk" type="checkbox" value="20"> <input class="chk" type="checkbox" value="30"> <button>Submit</button>
在 ID 的值中使用數字、標點符號或特殊字符可能會在其他上下文中引起問題(例如,CSS、JavaScript、正則表達式)。
例如,以下 ID 在 HTML5 中有效:
<div id="1"> ... </div>
但是,它在 CSS 中無效,因為選擇器不能是數字或以數字開頭,但可以介於中間或以數字結尾。
因此,只需更改 html 中的 ID 屬性值,以及您在 javascript 中引用它們的位置。 一定不要錯過任何分號
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.