StuBlackett
StuBlackett

Reputation: 3857

Prevent selecting more than X elements

I'm using jQuery to allow a user to select 3 time blocks and no more.

Once they've selected the 3 blocks, I'd like to prevent them from selecting more.

I am however, not having too much luck with it.

My current code can be found here : https://jsfiddle.net/1q8mzbwv/

I am trying an increment value of selected_num and adding a return false, but it's not preventing the selection.

I'd also like to try do this in reverse, where the user can click the selected item and the count changes too.

jQuery code :

var selected_num = 0;

$('.time-block').click(function()
{
var id = $(this).data('id');
var chosen_time = $(this).data('time');

$(this).addClass('-chosen');

$('.time-selected-block').eq(selected_num).html(chosen_time);

if(selected_num == "3")
{
    return false;
}
else
{
    selected_num++;
}

console.log(selected_num);
})

Thanks

Upvotes: 0

Views: 59

Answers (2)

Levizar
Levizar

Reputation: 85

In addition to the solution that was provided to you, here are some explanations:

Your problems are these:

1) This statement

$(this).addClass('-chosen');

appears before your evaluation. Thus, the class is added before the condition had the chance to be evaluated.

2) Your condition is working but is problematic:

selected_num == "3"

First, you want to prevent addition if more than 2 are selected: If by any chance, 4 would be selected, it would permit to add a 5th etc.

Second,you are comparing selected_num that is an integer with a string. This string is converted to an integer by the engine thus it's not a big deal but these type of conversion shouldn't be made if not intentional and useful.

3) As you have seen in the solution of Yevgen Gorbunkov, you should use "toggleClass" to add or delete the class in a shorter snippet.

Upvotes: 1

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15540

You may try the following:

$('.time-block').click(function () {
    if ($('.-chosen').length < 3 || $(this).hasClass('-chosen')) {
        $(this).toggleClass('-chosen')
    }
})

Here's the modified jsfiddle.

Upvotes: 1

Related Questions