Optgroup select title of group

I want to create a drop-down list with grouped items. This is for the HTML database search form I'm working with. Is there a way so that I can select the name of the group, which leads to the selection of all the elements in this particular group? For example, if the group name is “German cars” and it has the items “Mercedes” and “Audi”, by clicking “German cars”, you should select both German car companies.

+4
source share
2 answers

If you give your groups an opt-class class, you can select a class and then access its children.

$('.german-cars').children(); 

If this is not available, the alternative is a bit slow. When you go through all the groups of optgroups and compare their text each time, take those of them children.

edit: Set selector. And development:

Then, to select them when clicked, you will use:

 $('.german-cars').click(function(e) { e.preventDefault(); $(this).children().attr('selected', 'selected'); }); 

Assuming the item is set to multiple selection. Otherwise, only the last car in the list will be selected.

EDIT 2

Fiddle: http://jsfiddle.net/mbChZ/25/

These changes should work the way you are looking.

 $(function() { $('select optgroup').mousedown(function(e) { e.preventDefault(); if ($(this).children(':selected').length == $(this).children().length) { $(this).children().attr('selected', null); } else { $(this).children().attr('selected', 'selected'); } }); $('select option').mousedown(function(e) { e.stopPropagation(); e.preventDefault(); $(this).attr('selected', ($(this).is(':selected'))? null : 'selected'); }); });​ 

I changed the events to mousedown so that we can see the state of the elements before the browser has already processed the mousedown event. This allows us to check whether they are all selected, and if so cancel the selection, and not choose. And the same thing had to be done for the click option event to prevent this event from propagating.

I'm not 100% compatible with the browser on this, although you can make sure that it works in older IE if you support it.

+1
source

Not in any reliable form. optgroup is only for grouping options, not for influencing functionality. But you can use a set of flags instead of select elements, and then you can have a flag for "German cars" and, for example, indented below it, flags for different models of German cars.

Then you can deal with this in different ways. You can simply cope with the situation on the server side, so that if the "German cars" were checked, the form handler acts as if every flag for the German car was selected. Or can you also have a client-side handler for the “German cars” checkbox so that its check checks individual flags (but if it unchecks them when the checkbox is unchecked)?

0
source

Source: https://habr.com/ru/post/1396666/


All Articles