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 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.
You have to add event listener
on change of the checked
value of checkbox
$("#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.
<!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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.