Clams Are Great
Clams Are Great

Reputation: 280

Javascript/jQuery limiting toggleClass to 4

I'm trying to stop a user from selecting more than four free seats with toggleClass and a length attached but can't accomplish this and haven't found a solution that works for. Thanks.

JSfiddle
https://jsfiddle.net/xgrorxnp/1/

HTML

  <td class='n' id='1_A'>T</td>
  <td class='n' id='1_B'>F</td>
  <td class='n' id='1_C'>T</td>
  <td class="row_num">1</td>
  <td class='n' id='1_D'>T</td>
  <td class='n' id='1_E'>F</td>
  <td class='n' id='1_F'>T</td>

My Attempt

$('.n:contains(\'F\')').click(function(){
        var $this = $(this);
    $(this).toggleClass('selected', !$this.hasClass('selected') &&
        $('.n:contains(\'F\') .selected').length < 4);
    });

Upvotes: 0

Views: 36

Answers (1)

guest271314
guest271314

Reputation: 1

The issue is the space within selector $('.n:contains(\'F\') .selected'), which attempts to match .n element which has descandant .selected , rather than .n which has .selected className itself

Try substituting

$('.n:contains(\'F\').selected', this.parentElement)

for

$('.n:contains(\'F\') .selected').length < 4);

e.g.;

    $(this).toggleClass('selected', !$this.hasClass('selected') &&
        $('.n:contains(\'F\').selected', this.parentElement).length < amount);

where this.parentElement is the context to match, or the parentElement : tr element of clicked td element

jsfiddle https://jsfiddle.net/xgrorxnp/3/

Upvotes: 1

Related Questions