在項目中難免會遇到一些表單的提交,尤其是多選框中,當用戶選擇了某一項時,禁止其他項的選擇。所以為了避免這樣的沖突,所以我們前端就得控制一下了,下面就來個簡單demo,記錄一下,有需要的伙伴可以拿去耍耍~~
1、先放一張極丑的demo效果圖:
2、html代碼:
<body> <div class="mybox"> <p>1、請選擇你喜歡吃的甜品:</p> <input type="checkbox" class="mycheckbox" name="mycheck" value="雪糕"/>雪糕 <input type="checkbox" class="mycheckbox" name="mycheck" value="蛋糕"/>蛋糕 <input type="checkbox" class="mycheckbox" name="mycheck" value="無"/>無 </div> <div class="mybox"> <p>1、請選擇你喜歡的運動:</p> <input type="checkbox" class="mycheckbox" name="mycheck" value="滑雪"/>滑雪 <input type="checkbox" class="mycheckbox" name="mycheck" value="爬山"/>爬山 <input type="checkbox" class="mycheckbox" name="mycheck" value="無"/>無 </div> <div class="mybox"> <p>1、請選擇你喜歡吃的美食:</p> <input type="checkbox" class="mycheckbox" name="mycheck" value="燒烤"/>燒烤 <input type="checkbox" class="mycheckbox" name="mycheck" value="海鮮"/>海鮮 <input type="checkbox" class="mycheckbox" name="mycheck" value="無"/>無 </div> <div><button id="commit">提交</button></div> </body>
3、script 代碼:
<script type="text/javascript"> for(var i = 0 ; i < $(".mybox").length; i++){ for(var j = 0 ; j < $(".mybox")[i].childNodes.length; j++){ $(".mybox")[i].childNodes[j].onclick = function(){ if($(this)[0].nextSibling.nodeType == 3 && $.trim($(this)[0].nextSibling.textContent) == "無"){ if(this.checked){ $(this).siblings().prop("disabled",true) $(this).siblings().prop("checked",false) } else{ $(this).siblings().prop("disabled",false) } } } } } $("#commit").click(function(){ $("input[name='mycheck']:checked").each(function(){ $("body").append(this.value+"、") }) }) </script>