Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using jQuery and selectize.js library, and I have a select tag with 2 optgroups. Now, I need to check which optgroup is chosen from the option chosen, or maybe in another words, get the value of the optgroup when the user choose an option. Here is the code:
<select id="test">
    <optgroup value="100" label="Swedish Cars">
      <option value="volvo">Volvo</option>
      <option value="saab" selected>Saab</option>
    </optgroup>
    <optgroup value="101" label="German Cars">
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </optgroup>
  </select>

$(function() {
	$('#test').selectize();
  var selected = $('select option:selected');
  $("#test").change(function(){
  alert(selected.closest('optgroup').attr('value'));
});
});

But I am getting undefined on alert. How do I do this?

What I have tried:

Here is the fiddle: Edit fiddle - JSFiddle - Code Playground[^]
Posted
Updated 14-Sep-22 22:24pm

1 solution

First problem: the Selectize plugin removes all <optgroup> elements from the DOM. Your selected <option> is the only child element of the <select>.

You can use the Selectize API to get a reference to the element it uses to represent the selected option, and from there get the element it uses to represent the group:
JavaScript
$(function() {
	const test = document.getElementById("test");
	const $test = $(test);
	
	$test.selectize();
	const api = test.selectize;
	
	$test.change(function(){
		const selected = api.getOption(test.value);
		const optgroup = selected.closest("div.optgroup");
		alert(optgroup.attr("data-group"));
	});
});
But that brings you on to the second problem: an <optgroup> doesn't have a value attribute. Selectize only copies the label attribute to the data-group attribute on its grouping element; all other attributes will be discarded.

You can't even get around the problem by adding data- attributes to the option elements, since the Selectize plugin discards those as well.

You'll need to ask the author(s) whether what you're trying to do is possible with their plugin:
Issues · selectize/selectize.js · GitHub[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900