samedi 22 juin 2019

what's wrong with this jQuery addClass

I'm new to jQuery and have been fine with some simple codes but this one is puzzling me.

I have a list of checkboxes and I need to count the number of checked ones and display the count in a textbox. I want to add different class according to the count.

If 1 or 2 then class .blue If 3 or more then class .red If 0 AND a "none of the above" checkbox is checked then class .green * The "none of the above" checkbox has to be checked to add the class .green. A value of "0" is not enough. I need the user to be aware and sure of the "none of the above".

I managed to make it work and to make the checked status toggle between the "none of the above"and the rest.

I'm still puzzled by the addClass malfunctioning as follows:

What I expect is: When I click 1 or 2 checkboxes, the class goes blue. If I click a third one then it goes red. If I unchecked one, then it goes back to blue. If unchecked all then no style. If checked the "none of the above" then it goes green. If I uncheck any checkbox then the class should go back to the previous status.

This is what I'm getting: I'm not getting the '.red' class when 3 or more are checked. If I uncheck any checkbox, the class stays the same. If I uncheck all and regardless of the "none of the above", it goes ".green"!

This is my code:

$('input:checkbox').change(function() {
  var a = $("input.ab:checked").length
  $(".count").val(a);
  var count = $(".count").val(a);
  var res = '0';
  var nota = $('input.nota:checked');

  if (a < 1 && nota) {
    var res = ('green');
  } else if (a < 3 && a > 0) {
    var res = ('blue');
  } else if (a => 3) {
    var res = ('red'); // not working !
  }
  count.addClass(res);
});
// toggle checked
$("input.ab").change(function() {
    $("input.nota").not(this).prop('checked', false);  
});

$("input.nota").on('change', function() {
    $(".count").val(0)
    $("input.ab").not(this).prop('checked', false);    
});

Html:

<div>
  <h4>Count checked, toggle, add class to each result</h4>
  <u>
    <li class='gr'> If "None of the above" is checked then: GREEN </li>
    <li class='bl'> If count = 1 or 2 then: Blue </li>
    <li class='rd'> If count 3 or more then: Red </li>
  </u>
  <p>
    <input type='checkbox' class='ab'>AB
  </p>
  <p>
    <input type='checkbox' class='ab'>ABC
  </p>
  <p>
    <input type='checkbox' class='ab'>ABDC
  </p>
    <p>
    <input type='checkbox' class='ab'>ABCDEF
  </p>
  <p>
    <input type='checkbox' class='nota'> None of the above (HAS TO be checked to be green)
  </p>
  <p>
    Count: <input type='text' class='count'>
  </p>
</div>

This is the jsfiddle : http://jsfiddle.net/A888/h83z0knf/

Thank you. Please remember I'm a newbie here and in jQuery so please ask me to clarify or fix or even delete my post before you down-vote me. I tried my best before posting.




Aucun commentaire:

Enregistrer un commentaire