簡體   English   中英

切換兩個復選框

[英]Toggle two checkboxes

我有兩個復選框,每個復選框分別處理垂直和水平狀態。 如果兩個都關閉也可以,但是如果一個打開另一個必須關閉,最重要的是兩個都不能打開。

我不想在這里使用 jQuery。

如果我都未選中並且我先點擊了水平方向然后點擊了垂直方向,它們將切換,因為水平方向未選中而垂直方向將變為選中狀態。

但是,如果我從垂直方向開始以另一種方式進行操作,則無法檢查水平方向。

完整代碼在github 上,演示在gh-pages上運行。

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Toggle</title> </head> <style> .constraint { color: #007bff; padding: 0rem .5rem; } span.horz:before { content: "\\2194"; } span.vert:before { content: "\\2195"; } </style> <body> <span class="constraint">Constraint: </span> <span class="constraint vert"> <input type="checkbox" id="vertical" onchange="constraints()"> <span class="constraint horz"></span> <input type="checkbox" id="horizontal" onchange="constraints()"> </body> <script type="text/javascript"> function constraints() { inputVert = document.getElementById("vertical"); inputHorz = document.getElementById("horizontal"); console.log("initially: vert:" + inputVert.checked); console.log("initially: horz:" + inputHorz.checked); if (inputVert.checked) { console.log("vert clicked -> vert:" + inputVert.checked); console.log("vert clicked -> horz:" + inputHorz.checked); // inputHorz = document.getElementById("horizontal"); inputHorz.checked = false; // inputVert.checked = true; }; if (inputHorz.checked) { console.log("horz clicked -> vert:" + inputVert.checked); console.log("horz clicked -> horz:" + inputHorz.checked); // inputVert = document.getElementById("vertical"); inputVert.checked = false; // inputHorz.checked = true; }; } </script> </html>

非常感謝任何幫助,

謝謝

使用 JQuery 你可以這樣做,希望這對你有幫助

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Toggle</title> </head> <style> .constraint { color: #007bff; padding: 0rem .5rem; } span.horz:before { content: "\\2194"; } span.vert:before { content: "\\2195"; } </style> <body> <span class="constraint">Constraint: </span> <span class="constraint vert"> <input type="checkbox" id="vertical"> <span class="constraint horz"></span> <input type="checkbox" id="horizontal"> </body> <script type="text/javascript"> $('#vertical').change(function() { if($(this).is(":checked")){ $('#horizontal').attr('checked', false); } }); $('#horizontal').change(function() { if($(this).is(":checked")){ $('#vertical').attr('checked', false); } }); </script> </html>

這是使用輸入收音機的經典場景。 這迫使用戶最多選擇一個選項。 https://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio

根據@Leonardo 的回答,您可以將其進一步簡化為以下內容:

$('#vertical').on("change", function() {
   $('#horizontal').attr('checked', !$(this).is(":checked"));
});
    
$('#horizontal').on("change", function() {
   $('#vertical').attr('checked', !$(this).is(":checked"));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM