checkbox - jQuery: checkboxes checked, conditional setup -
i'm trying set comditions showing , hiding elements depending on state of 2 checkboxes:
- if checkbox
achecked, display element class.one. hide elements class.two. - if checkbox
bchecked, display element class.two. hide elements class.one. - if both checked, display both elements.
- if none of them checked, hide both elements.
my code below. checkboxes same except value. have trouble logic checking both checkboxes.
html:
<form action=""> <div class="inputfield"> <label for="">a</label> <input type="checkbox" name="xyz" value="a" /> <label for="">b</label> <input type="checkbox" name="xyz" value="b" /> </div> </form> <div class="one">results a</div> <div class="one">results a</div> <div class="two">results b</div> js:
var = $(".one"); var b = $(".two"); a.hide(); b.hide(); $(".inputfield input[name='xyz']").change(function() { var value = $(this).val(); if (this.checked) { //console.log(value); if (value == 'a') { a.show(); b.hide(); } if (value == 'b') { a.hide(); b.show(); } if (value == 'a' && value == 'b') { a.show(); b.show(); } } else { a.hide(); b.hide(); } });
you can instead use toggle() , is(':checked'). can use attribute selector select each input value attribute , toggle one , two div's
var = $(".one"); var b = $(".two"); a.hide(); b.hide(); $(".inputfield input[name='xyz']").change(function() { a.toggle($('input[value="a"]').is(':checked')) b.toggle($('input[value="b"]').is(':checked')) }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action=""> <div class="inputfield"> <label for="">a</label> <input type="checkbox" name="xyz" value="a" /> <label for="">b</label> <input type="checkbox" name="xyz" value="b" /> </div> </form> <div class="one">results a</div> <div class="one">results a</div> <div class="two">results b</div>
Comments
Post a Comment