![](/img/trans.png)
[英]How to check whether user has checked at least one checkbox from a group of checkboxes using jQuery/Javascript?
[英]JavaScript to allow either one checkbox or from a group of checkboxes
我有一個帶有四個復選框的 div,應該允許用戶選擇第一個復選框或兩個、三個和四個的組合,但不能一起選擇。 示例場景:
div 是這樣的:
<div class="question" id="someFilters">
<label>Some Suppliers</label>
<div class="someclass">
<form:checkbox id="firstcheckbox" value="First checkbox"/>
<label class="inputtext">First Checkbox</label>
<form:checkbox id="secondcheckbox" value="Second checkbox"/>
<label class="inputtext">Second Checkbox</label>
<form:checkbox id="thirdcheckbox" value="Third checkbox"/>
<label class="inputtext">Third Checkbox</label>
<form:checkbox id="fourthcheckbox" value="Fourth checkbox"/>
<label class="inputtext">Fourth Checkbox</label>
</div>
</div>
任何幫助深表感謝。
您描述的條件的邏輯很簡單:
不得選中第一個框或不得選中所有其他框。
將根據是否滿足該條件為該腳本中的valid
變量分配一個布爾值。 這個賦值語句有效,因為變量cs
之前已經被分配了一個包含所有輸入元素的 NodeList(通過.querySelectorAll("input")
- 盡管你可能想要使用一個選擇器,它按名稱或類或其他一些元素來定位元素)屬性。)
請注意,您發布的 html 格式不正確。 具體來說, <form:checkbox />
不代表一個 html 元素。
const cs = document.querySelectorAll("input"); document.querySelector("button").addEventListener("click", validate); function validate(){ const valid = !cs[0].checked || !cs[1].checked && !cs[2].checked && !cs[3].checked; console.log(valid ? "good" : "bad"); }
<input type="checkbox" />1 <input type="checkbox" />2 <input type="checkbox" />3 <input type="checkbox" />4 <br /> <button type="button">Validate</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.