domino
domino

Reputation: 7345

jquery - limiting toggleClass to 2 elements

<script type="text/javascript">
        $(document).ready(function () {
            $('#mytable td').click(function () {
                $(this).toggleClass('newclass');

            });
        });
    </script>

This function changes the class of the selected column in my table. It works fine.

However it should not allow more than 2 columns being selected at once (by selected I mean the column having the new class toggled - newclass). So it simply should not react if other columns are clicked.

How would I do this? I could count how many columns currently use newclass and if it's 2 then cancel the function. I'm not sure how to count them or if this is the best way to do it.

Upvotes: 0

Views: 356

Answers (4)

MikeM
MikeM

Reputation: 27415

here's one way to ensure no more than 2

jsfiddle

$('#mytable td').click(function() {
    var $this = $(this);
    // toggle 'on' if
    // 1. it doesn't already have the class and
    // 2. and there are less than two set to .newclass
    // toggle 'off' if
    // 1. it already has the class and
    // 2. and there are less than two set to .newclass
    $this.toggleClass('newclass', 
        !$this.hasClass('newclass') && 
        $('#mytable .newclass').length < 2);
})

Upvotes: 2

Keith.Abramo
Keith.Abramo

Reputation: 6965

<script type="text/javascript">
    $(document).ready(function () {
        $('#mytable td').click(function () {
            if(!$(this).hasClass('newClass')){
                if($("td.newClass").size() < 2){
                    $(this).toggleClass('newclass');
                }
            }
            else {
                 $(this).toggleClass('newclass');
            }
        });
    });
</script>

Upvotes: 1

dSquared
dSquared

Reputation: 9825

Try using the length property like this:

<script type="text/javascript">
    $(document).ready(function () {
        $('#mytable td').click(function () {
            if ($('#mytable td.newclass').length < 2)){                
                $(this).toggleClass('newclass');
            }
        });
    });
</script>

Hope this helps!

Upvotes: 1

Michael Low
Michael Low

Reputation: 24506

The size() method shows you how many other elements match that selector, so you can test against that before applying toggleClass():

<script type="text/javascript">
    $(document).ready(function () {
        $('#mytable td').click(function () {
           if ($("#mytable td.newclass").size() < 2) 
           { 
               $(this).toggleClass('newclass');
           }

        });
    });
</script>

Upvotes: 1

Related Questions