whatevermike
whatevermike

Reputation: 196

Update variable as class changes

I have the following code which changes a <div> area and displays correctly, but does not update when the variable changes.

var count = $('.selection').length;
$('#div').text(count);

As I understand things, the variable is calculated when the code is ran (before any .selection changes). I tried to put the above into my click handler (below) but need some help in making things work.

$('#tbl td.n').bind('click', function() {
  sb = $('.selection').length;
  if (sb == 10 && !$(this).hasClass('selection')){
    alert("Please select less than 10");
    return;
  };
  $(this).toggleClass('selection n');
});

Upvotes: 0

Views: 38

Answers (1)

baao
baao

Reputation: 73241

You need to recheck the count after the class was toggled. Also, as your alert says 'select less than 10' I think you are looking for an if check like

if (sb >= 10 && !$(this).hasClass('selection'))


$('#tbl td.n').bind('click', function() {
  sb = $('.selection').length;
  if (sb >= 10 && !$(this).hasClass('selection')){
    alert("Please select less than 10");
    return;
  };
  $(this).toggleClass('selection n');
  count = $('.selection').length;
  $('#div').text(count);  
});

Upvotes: 1

Related Questions