Reputation: 1039
I have 3 checkboxes and need user to select atmost one at a time, so have a code where everytime user selects one of my checkboxes. I deselect all other and check the selected one using:
$('input.myclass').click(function () {
$('input.myclass:checked').not(this).removeAttr('checked');
});
Just below this code, I also get value of checked checkbox and display it somewhere on page (for simplicity sake, let it be alert). For that I am using:
var sFilter = "";
$('input.myclass[type=checkbox]').each(function () {
sFilter = sFilter + (this.checked ? $(this).val() : "");
});
Now, what happening is sFilter
always has recently selected checkbox and last selected checbox. like: If I have checkbox 1,2,3. Initially when I select checkbox 2, I get 2 in my alert, but when I choose 3 , I get 2,3. I presume whats happening here is at a point where code goes through all the checkbox with particular class, it stills thinks that I have checkbox 2 checked
considering I have just cleared/unchecked using click
function.
Does anyone has suggestion on how i can get around this problem?
Thanks
NB: Cant use radio-buttons due to UI.
Upvotes: 0
Views: 1489
Reputation: 2150
Why not try something like this (here's the jsFiddle):
var sFilter = "";
$('input.myclass').click(function () {
$('input.myclass:checked').not(this).removeAttr('checked');
sFilter = (this.checked ? $(this).val() : "");
alert(sFilter);
});
Each time you click, you update sFilter
and then do whatever you want with it.
If you don't want to "alert" when you deselect, then try something like:
var sFilter = "";
$('input.myclass').click(function () {
$('input.myclass:checked').not(this).removeAttr('checked');
sFilter = (this.checked ? $(this).val() : "");
if (sFilter != "") alert(sFilter);
});
Upvotes: 1
Reputation: 687
One solution possible is that you loop through these checkboxes on the click event of these checkboxes.
Even if you loop through them on say a button's click you will be fine.
Check this Jsfiddle-http://jsfiddle.net/LMgFz/
$('input.myclass').click(function () {
$('input.myclass:checked').not(this).removeAttr('checked');
var sFilter = "";
$('input.myclass[type=checkbox]').each(function () {
sFilter = sFilter + (this.checked ? $(this).val() : "");
});
alert(sFilter);
});
If it makes sense?
Upvotes: 2