![](/img/trans.png)
[英]How to hide content when checkbox is checked and show when checkbox is unchecked?
[英]How to hide/show part of a form when checkbox is checked/unchecked?
這是我嘗試用javascript隱藏和顯示表單部分的第一次嘗試。 我在javascript方面有0年的經驗,並且在過去的2-3個小時內在其他幾個網站和教程的頂部嘗試了本教程和該基本示例 ,但所有方法都無法真正起作用。
我制作了一個包含多個收音機,幾個文本字段和幾個復選框的表單。 我希望其中一些文本字段不可見,直到您選中將顯示它們的特定復選框。 我想對多個文本字段的多個復選框執行此操作。
示例:選中復選框“其他”,然后出現一個文本字段,告訴您在該字段中指定其他。
我不想將所有問題都分享給我,而是希望通過一種簡單的方法來弄清楚如何使其工作,下面將代碼的范圍縮小為一個小測試。 根據“基本示例”,我將“被隱藏/顯示”部分放在div
是因為我認為這可能會有所幫助,但是對於我的表單,不必在div
中。
在此先感謝您的答復,並為我的no昧致歉:)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script> $("#yourCheckboxID").click(function () { if ($("#boxchecked").attr("checked")) { $("#hidden").show(); } else { $("#hidden").hide(); } }); </script> </head> <body> <form id="form1" name="form1" method="post" action=""> <p> <label> <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="box" /> Main.</label> <br /> <label> <input type="checkbox" value="checkbox" name="CheckboxGroup1" id="boxchecked" /> Other.</label> <br /> </p> </form> <div id="hidden">Can you see this?</div> </body> </html>
謝謝!
您可以使用CSS來實現,請使用psuedo選擇器:
.inputs { display: none; } .foo:checked + .inputs { display: initial; }
<form action="foo"> <input type="checkbox" class="foo"> <div class="inputs"> bla blah inputs <input type="text"> <textarea name="" id="" cols="30" rows="10"></textarea> </div> </form>
使用$("#boxchecked").is(':checked')
$(document).ready(function(){
$("#boxchecked").click(function ()
{
if ($("#boxchecked").is(':checked'))
{
$("#hidden").show();
}
else
{
$("#hidden").hide();
}
});
});
小提琴鏈接: https : //jsfiddle.net/san6gc9c/
另一個選擇是使用jQuery的prop函數:
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script>
$(document).ready(function(){
$("#boxchecked").click(function (){
if ($("#boxchecked").prop("checked")){
$("#hidden").hide();
}else{
$("#hidden").show();
}
});
});
</script>
<script> $(document).ready(function () { $("#a").click(function () { if ($("#a").prop("checked")) { $("#b").hide(); $("#c").hide(); $("#d").hide(); $("#e").hide(); } else { $("#b").show(); $("#c").show(); $("#d").show(); $("#e").show(); } }); }); <script>
<div><input id="a" type="checkbox"></div> <div><input id="b" type="checkbox"></div> <div><input id="c" type="checkbox"></div> <div><input id="d" type="checkbox"></div> <div><input id="e" type="checkbox"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.