Reputation: 331
We have a selectize field where multiple values can be selected. These values are grouped in optgroups. To ease understanding, some values can be in multiple optgroups, we would like to see the name of the optgroup in the labels for the selected fields, too. How can we accomplish this?
See following fiddle, if you select "First Item" you do not know which one was selected, Store or Warehouse.
Thanks!
https://jsfiddle.net/4t8fjj7g/1/
HTML:
<select name="test" id="test-select" multiple="multiple">
<optgroup label="Store">
<option data-type="stores" value="1">First item</option>
<option data-type="stores" value="2">Second item</option>
</optgroup>
<optgroup label="Warehouse">
<option data-type="warehouses" value="3">First item</option>
<option data-type="warehouses" value="4">Second item</option>
</optgroup>
</select>
And this is the javascript code:
$('select#test-select').selectize({
searchField: ['text', 'type']
});
Upvotes: 0
Views: 1621
Reputation: 793
What I did is have the values have the optgroup then the value like optgroup_value
then when the form gets submitted on the server or doing something in JS I can get it by exploding the string like:
<select multiple class="my-select">
<optgroup label="taxes">
<?php foreach ( $taxes as $tax) : ?>
<option value="tax_<?php echo $tax->slug; ?>"><?php echo $tax->name; ?></option>
<?php endforeach; ?>
</optgroup>
<optgroup label="Version">
<?php foreach ( $my_versions as $version ) : ?>
<option value="version_<?php echo $version->slug; ?>"><?php echo $version->name; ?></option>
<?php endforeach; ?>
</optgroup>
<optgroup label="Language">
<?php foreach ( $my_languages as $language ) : ?>
<option value="language_<?php echo $language->slug; ?>"><?php echo $language->name; ?></option>
<?php endforeach; ?>
</optgroup>
</select>
then
<?php
foreach ( $_POST['taxes'] as $val ) {
if ( ! empty( $val ) ) {
// $val_parts is an array with
// $val_parts[0] = optgroup only
// $val_parts[1] = the value of the option minus optgroup
$val_parts = explode( "_", $val );
// My use case to add a meta_query to a WP_Query so add filter based on both values
$meta_arg = array(
'taxonomy' => "my_" . $val_parts[0], // custom prefix then optgroup
'field' => 'slug',
'terms' => $val_parts[1] // value
);
// Add to running array and possibly do again
array_push( $args['tax_query'], $meta_arg );
}
}
Upvotes: 0
Reputation: 11
Basically, what Daffy has suggested, BUT... You can use custom rendering functions for dropdown options and for selected items:
$('select#test-select').selectize({
searchField: ['text', 'type'],
render: {
item: itemRenderFunction,
option: optionRenderFunction
}
});
This will allow you to avoid label multiplication in selected items list.
Upvotes: 1