Reputation: 326
I am trying to select multiple rows (limited) in the table. I can select and receive data from that selection now but I would like to limit my selection. I would like to create a table that user can select only 6(limited) rows. After 6 rows are selected, I want to stop click event.
I tried like this but it doesnt work because event can not be stopped.
var selectedRows = 0;
if(selectedRows < 6) {
$("#table1 tr").click( function(){
if($(this).hasClass("selected")) console.log("already chosen");
else {
$(this).addClass("selected");
var id = $("th",this).html();
selectedRows++;
console.log(selectedRows, teamNo);
}
});
} else {
console.log("you've chosen 6 rows !");
}
edit: Also I want to add this feature.
If the user selects 6 rows and s/he continues to select more, the first selection changes with 7th selection and so on.
Upvotes: 1
Views: 2188
Reputation: 68943
Try the condition inside the function:
var selectedRows = 0;
$("#table1 tr").click( function(event){
if($(this).hasClass("selected")) console.log("already chosen");
else {
if(selectedRows <= 6) {
$(this).addClass("selected");
var id = $("th",this).html();
selectedRows++;
console.log(selectedRows, teamNo);
}
else {
console.log("you've chosen 6 rows !");
}
}
});
Upvotes: 1
Reputation: 292
You need to check if the user has selected more than 6 WITHIN the click function, and then fire the actions IF the user has not selected 6. You just have it flipped.
$("#table1 tr").click( function(){
if(selectedRows <= 6) {
if($(this).hasClass("selected")) console.log("already chosen");
else {
$(this).addClass("selected");
var id = $("th",this).html();
selectedRows++;
console.log(selectedRows, teamNo);
}
} else {
console.log("you've chosen 6 rows !");
}
});
Upvotes: 0