简体   繁体   English

基于选中的复选框的jquery简单隐藏显示

[英]jquery simple hide show based on checkbox checked

I want to show and hide the options inside the main based on checkbox checked or not.我想根据是否选中复选框来显示和隐藏主文件中的选项。 I have many checkbox but here I am checking address checkbox.我有很多复选框,但在这里我正在检查地址复选框。

This is my checkbox这是我的复选框

<input type="checkbox" id="address">Mark it

here is div I want to hide/show这是我想隐藏/显示的 div

<div id="options">
//div
</div>

 if($('#address').prop('checked')){
        $('#options').show()
      }else{
        $('#options').hide()
      }

Above code is not working for me.上面的代码对我不起作用。

Your code will only work on the first time not every time the value of the checkbox changes.您的代码仅在第first time而不是在复选框的值每次更改时生效。

You have to add event listener on change of the checked value of checkbox您必须在更改复选框的checked值时添加event listener

$("#address").on("change", e => {
  const isChecked = e.target.checked;
  if (isChecked) $('#options').show()
  else $('#options').hide()
})

 if ($('#address').prop('checked')) { $('#options').show() } else { $('#options').hide() } $("#address").on("change", e => { const isChecked = e.target.checked; if (isChecked) $('#options').show() else $('#options').hide() })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="address">Mark it <div id="options"> //div </div>

The reason your code not working, you only check the condition checkbox check or not you have to call the checkbox change event also every time when the checkbox gets clicked.您的代码不起作用的原因,您只检查条件复选框检查或不每次单击复选框时也必须调用复选框更改事件 here is a working demo hope it will help you to understand how jquery works.这是一个工作演示,希望它可以帮助您了解 jquery 的工作原理。

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function () { $('#options').hide(); $('#address').change(function () { if ($('#address').prop('checked')) { $('#options').show() } else { $('#options').hide() } }); }); </script> </head> <body> <div id="options"> //div </div> <input type="checkbox" id="address">Mark it </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM