vendredi 18 août 2017

jQuery: checkboxes checked, conditional setup

I'm trying to set up some comditions for showing and hiding elements depending on the state of two checkboxes:

  • If checkbox A is checked, display element with the class .one. Hide elements with class .two.
  • If checkbox B is checked, display element with the class .two. Hide elements with class .one.
  • If both are checked, display both elements.
  • If none of them are checked, hide both elements.

My code is below. The checkboxes are the same except for their value. I have trouble with the logic for 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 for A</div>
<div class="one">Results for A</div>
<div class="two">Results for B</div>

Js:

var a = $(".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();
  }
});

JsFiddle here.




Aucun commentaire:

Enregistrer un commentaire