I have the following code:
$(document).ready(function () {
$("#comboSubsidiary").combobox({
selected: function (event, ui) {
var subsidiary = $("#comboSubsidiary").select().val();
switch (subsidiary) {
case (subsidiary = "GH"):
$.ajax({
type: "GET",
url: "GHworkerType.xml",
dataType: "xml",
success: function (xml) {
var select = $('#comboWorkerType');
$(xml).find('type').each(function () {
var type = $(this).find('type').text();
select.append("" + type + "");
var id = $(this).attr('id');
var name = $(this).find('name').text();
var rate = $(this).find('rate').text();
if (name == "Cust" || name == "Int") {
$('<optgroup label="' + name + '"></optgroup>').html(name).appendTo('#comboWorkerType');
}
else {
$('<option>' + name + '</option>').html(name).appendTo('#comboWorkerType');
}
});
select.children(":first").text("Select worker type").attr("selected", true);
}
});
break;
case (subsidiary = "GT"):
alert('Alert');
break;
}
}
});
});
HTML:
<div class="comboTravel">
<select id="comboSubsidiary" >
<optgroup label="Cust">
<option>Select subsidiary</option>
</optgroup>
</select>
</div>
this is the XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worker>
<type>
<name>Cust</name>
<rate>Cust</rate>
</type>
<type>
<name>1</name>
<rate>75</rate>
</type>
<type>
<name>2</name>
<rate>83</rate>
</type>
<type>
<name>3</name>
<rate>105</rate>
</type>
<type>
<name>4</name>
<rate>115</rate>
</type>
<type>
<name>5</name>
<rate>0</rate>
</type>
<type>
<name>Int</name>
<rate>Int</rate>
</type>
<type>
<name>1</name>
<rate>75</rate>
</type>
<type>
<name>2</name>
<rate>83</rate>
</type>
<type>
<name>3</name>
<rate>105</rate>
</type>
<type>
<name>4</name>
<rate>115</rate>
</type>
<type>
<name>5</name>
<rate>0</rate>
</type>
</worker>
I want the combobox to show Cust and Int as optgroups. How can I get this to work?
At the moment all xml nodes were correctly displayed in the combobox but the two optiongroups aren't displayed and everything which is included to the optiongroups isn't displayed in the combobox.
Sorry it is not a complete solution but the standard combobox
does not allow loading data remotely, so rather than reinvent, here are some alternatives.
The answer to jQuery UI autocomplete (combobox): how to fill it with the result of an AJAX request? contains modified combobox
code in which you can specify a value array or remote source. In my opinion the jQueryUI combobox is really a hack and does not seem to be considered a first class widget.
You might have better luck using http://ivaynberg.github.com/select2/ which (again, in my opinion) has a richer API, looks cleaner and is overall a better UX. You will need to supply a formatResult
function to display your custom data but there are plenty of examples on the aforementioned link.
However, just one caveat is that <optgroup>
support has only recently be added, so you will need the latest Select2 3.0 build, which could be unstable.
Hope this helps :-)