snapappointments / bootstrap-select

:rocket: The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more.
https://developer.snapappointments.com/bootstrap-select/
MIT License
9.84k stars 2.72k forks source link

Error when have a class attribute for optgroup tag #2859

Open walid-ajaj opened 5 months ago

walid-ajaj commented 5 months ago

https://github.com/snapappointments/bootstrap-select/blob/939e94b14a34759e193f616b753e0a33081cc0c5/js/bootstrap-select.js#L731

Browser will throw the error exception DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided must not be empty. when you have <optgroup /> with a value in class attribute.

Example: https://jsfiddle.net/9jbr5h0u/

<select class="selectpicker show-menu-arrow" data-live-search="true" title="Choose one of the following..." data-size="10" >
  <option>-- Select --</option>
  <optgroup label="Test Group" class="test-style">
    <option>Honda</option>
    <option>Civic</option>
    <option>Accord</option>
    <option>Odyssey</option>
  </optgroup>
</select>

The issue is: in line 1684 plugin try to add class name opt followed with a space. However, in line 1732 config.optgroupClass is already have a space followed with value <optgroup /> have a class attribute. This lead optionClass in line 1684 to have two class names separated with two spaces.

Now in line 731 the code classes.split() will create a an array which second element is an empty string, and that empty string element is the one cause the Exception when browser try to add it as class name.

My quick fix for this issue is to filter the result array and remove the empty elements: if (typeof classes !== 'undefined' && classes !== '') a.classList.add.apply(a.classList, classes.split(/\s+/).filter(function(x) {return x!==''}));

Not sure if there is other places could have same bug, but same fix cam be applied to eveywhere there is a split() call: https://github.com/snapappointments/bootstrap-select/blob/939e94b14a34759e193f616b753e0a33081cc0c5/js/bootstrap-select.js#L731 https://github.com/snapappointments/bootstrap-select/blob/939e94b14a34759e193f616b753e0a33081cc0c5/js/bootstrap-select.js#L2069 https://github.com/snapappointments/bootstrap-select/blob/939e94b14a34759e193f616b753e0a33081cc0c5/js/bootstrap-select.js#L2071 https://github.com/snapappointments/bootstrap-select/blob/939e94b14a34759e193f616b753e0a33081cc0c5/js/bootstrap-select.js#L2073 https://github.com/snapappointments/bootstrap-select/blob/939e94b14a34759e193f616b753e0a33081cc0c5/js/bootstrap-select.js#L2074

Regards,