The front end is a problem, there is no access to editing Html markup for certain reasons, but you need to merge options from select into an optiongroup tag, for example, I have points:

<select> <option data-group="first" value="test1"> <option data-group="first" value="test2"> <option data-group="second" value="test3"> </select> 

I need to convert to:

 <select> <optgroup label="first"> <option data-group="first" value="test1"> <option data-group="first" value="test2"> </optgroup> <optgroup label="second"> <option data-group="second" value="test3"> </optgroup> </select> 

The problem is that this select is custom through the bootstrap. Is it possible to do this through Js?

    1 answer 1

     var groups = {}; //собираем элементы по группам $('option[data-group]').each(function(i, el) { var group = $(el).data('group'); if (!groups.hasOwnProperty(group)) groups[group] = []; groups[group].push(el); }); //оборачиваем в новый тег for (var group in groups) { $(groups[group]).wrapAll('<optgroup label="' + group + '"/>'); } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option data-group="first" value="test1">test1</option> <option data-group="first" value="test2">test2</option> <option data-group="second" value="test3">test3</option> </select> 

    • super thank you, the problem is just that if there are spaces in the group name, it cuts off all the words after the space, what could be the reason? - zoinx2012
    • @ zoinx2012 now does not cut off - yolosora
    • hello again, I ran into a problem that this code is inadequate to select selects, that is, suppose if I prescribe selected at the first element, in fact, the second will be selected, what can be connected with? - zoinx2012 2:51 pm
    • @ zoinx2012 how did that come about? I could not reproduce - yolosora