My HTML code snippet:
<div class="item form-group">
<label class="col-md-3 col-sm-3 col-xs-12" for="middlename">Payee Code </label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="payee" name="payee" class="select2_multiple form-control"multiple="multiple">
{{range $key,$val := .payee}}
<option>{{$val.Code}}</option>
{{end}}
</select>
</div>
</div>
This select2 options are populated from the {{.payee}} value i send from backend golang program.
Now i want to auto select this select2 using the {{.Code}} variable (which is a []string) that i send from my program.I want to select all the options that matches with the values in {{.Code}}
Please help in achieving auto fill on select2. Thanks in advance.
I got the answer myself. This will help others who are stuck with the same kind of problem.
First Mistake option tag must have value specified
<option value={{$val.Code}}>{{$val.Code}}</option>
Let us consider an example the list of all the options(from $val.Code) are 141 , 152, 173, 184, 188 , 200 among these 141 and 173 are to be pre-selected from {{.Code}}}
script:
if( {{.Code}} != "")
{
$("#payee").val({{.Code}}).trigger("change");
}
This will select the options matching {{.Code}}.
Thanks all for the help.
I'm not really sure if i understand correctly what you want to achieve, but as soon as you populate your select box with the option values, you can add the selected option to each of them, if this is your objective.
Otherwise you can use conditional statement to check which of the values satisfies some condition and only for those of them to add the autoselected option.
<select id="payee" name="payee" class="select2_multiple form-control"multiple="multiple">
{{range $key,$val := .payee}}
<option>{{$val.Code}}{{if .Code}}selected="selected"{{end}}</option>
{{end}}
</select>