简体   繁体   中英

Show multiple div after click button only if checkbox are checked

I'd like to show one or two div after click a submit button, but only if first and/or second checkbox are checked. I have this code:

 var first = true; $('input[type="checkbox"][name^=chk]').change(function() { var $target = $('#sb' + this.id.replace('chk', '')).toggle(this.checked); if (first) { $('div[id^=sb]').not($target).hide(); first = false; } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input name="chk1" type="checkbox" id="chk1" value="">chekme1 <input name="chk2" type="checkbox" id="chk2" value="">checkme2 <div id="sb1" style="display: none;">Checkbox content one</div> <div id="sb2" style="display: none;">Checkbox content two</div>

I'm not expert on JavaScript. Is there a way to add a submit button to show the first or/and second div after click on button?

I guess the easiest way would be to implement onClick() event over the button with function that checks if checkbox is checked.

function showDiv(){
   if(document.getElementById('chk1').checked){ 
       $div1.show()
   } else {
       $div1.hide()
   }
   if(document.getElementById('chk2').checked){
       $div2.show()
   } else {
       $div2.hide()
   }
}

here you have working example: https://jsfiddle.net/j30reczv/24/

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.

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