Reputation: 12512
I have selector with multiple option grouped into option groups. I am trying to toggle select/deselect of all options when an optgroup label is clicked.
It works fine on initial load, but I also have a functionality that allows me to copy options from one selector to another and back. Once options are copied my toggle stops working.
$("optgroup").toggle(function(){
$(this).children().attr("selected", "selected");
}, function() {
$(this).children().attr("selected", false);
});
Here's the copy/remove script.
Upvotes: 0
Views: 10714
Reputation: 7297
This will not give you the desired UX, but it will solve the issue you are having with the toggle events getting unbinded: http://jsfiddle.net/rkw79/SwrVK/9/
$("select").delegate('optgroup', 'click', function() {
$(this).toggle(function() {
$(this).children().attr("selected", "selected");
}, function() {
$(this).children().attr("selected", false);
});
});
You can either use .live() or .delegate(); the problem is they only work with base events like 'click' or 'hover', and not derived events like 'toggle' (which is why it was wrapped above).
Note that this solution solves the unbinding issue, but in terms of UX, a few more tweaks are required.
Updated: UX additions http://jsfiddle.net/rkw79/SwrVK/15/
I think your intention is to select all the child options when a group is clicked. The code below will do that.
$("select").delegate('optgroup', 'click', function() {
$(this).children().attr("selected", "selected");
});
This chunk of code below will make it so that you can still select each child option independently. Events propagate up the node tree, so you have to prevent it (in this case).
$("select").delegate('option', 'click', function(e) {
e.stopPropagation();
});
Upvotes: 3
Reputation: 549
The problem has to do with the binding the toggle event. As the optgroups move in and out of selects, the events are no longer attached to the newly created optgroups. Sadly, there is no live binding for toggle events. You can hack something together that will get the job done with something like:
$("optgroup").live("click", function() {
var $children = $(this).children();
if($children.attr("selected")) {
$children.attr("selected", false);
} else {
$children.attr("selected", "selected");
}
});
Do keep in mind, this will bind the click event to any optgroups ever created on the page and could have some unforeseen side effects. I recommend using live with a class and not optgroup alone to mitigate this risk.
Upvotes: 3