Selectize option list population with data-data

3.3k views Asked by At

I am using selectize.js inside a form, and would like to populate the option list from within HTML. My understanding of the release notes for version 0.12.0 is that this should be possible using the "data-data" attribute, but I can’t make it work or find full working examples anywhere.

I was hoping to do something like this:

html:

<label for="leagues">Leagues:</label>
<input type="text" id="leagues" name="leagues" class="form-control" value='aaa' data-data="[{'info': 'aaa'},{'info': 'bbb'}]">

with js:

$('#leagues').selectize({
});

EDIT: I have got this working replacing ' with " so data-data is now:"[{"info":"aaa"},{"info":"bbb"}]"

FOLLOW ON: Now the option list is populated as expected, but it also overrides the value tag, so it doesn't seem possible render the control with an option-list of n items but with say 3 selected (Which seems to me to defeat the whole point of the dataAttr doesn't it????).

I can make this work using the States example for the documentation - but this uses rather than , so returning an array of values rather than a comma delimited list.

So...how do I implement a multi-select, POSTing a comma-delimited list, with the options set from HTML not js.

2

There are 2 answers

0
Bhavik Chauhan On

Finally got the solution using php data.

<option value="my_id" title="{{$category_name}}" data-data='<?php echo str_replace("'", "\'", json_encode(array('my_desc'=> {{$category_desc}})))?>'>{{$category_name}} </option>

In short you can write on this way :

$array_in_json = (json_encode($selected_array));
$array_ready_for_tag =str_replace("'", "\'", $array_in_json);

Finally :

<select data-data='<?php echo $array_ready_for_tag;?>' ... > ... </select>

Note : use single quote

0
Mohamed Fazal On

Selectize.js adding sub-text (hidden search fields is easy)

Create normal html options from jquery or raw html

value = {id:1, name:"sample_name", owner : "owner_name" .....}

<option value="${value.id}" data-data='${JSON.stringify(value)}' selected>${value.name} (${value.get_unit.short_form})</option>

$('#supplier_id').selectize({ searchField: ['name','owner', 'location', 'contact', 'email'], sortField: 'text' });

The searchField array will include content to be search.