Reputation: 632
I have a weird situation Accordigin to select 2 documentation I can manually assing a value using
$("#e1").select2("data",{id:"4", text: "some value" });
but when try to get the value using $("#e1").val() is returning null
Am I missing something?
Here a fiddle http://jsfiddle.net/mspasiuk/j69821ce/
Upvotes: 0
Views: 915
Reputation: 4903
Your code has 2 problems, the first is that when you need to add data from js code and not explicit in HTML (using <option>
tag), it's better to use an input
instead of select
and the second is you want to read selected data before selecting any data or event set an option as default.
So modify your HTML like this:
<input type="hidden" id="e1" style="width:200px;"/>
<br/><br/>
<input type="text" id="t1"></input>
<br /><br />
<input type="button" id="Submit" value="Submit" />
And JS like this:
$("#e1").select2({"data":[{id:"1", text: "some value 1" }, {id:"2", text: "some value 2" }]});
$("#Submit").click(function(){
$("#t1").val("option 1: "+ $("#e1").val());
});
Upvotes: 0
Reputation: 7328
According to the documentation, calling the data function "Gets or sets the selection." It does not actually create any options.
Here is an updated fiddle which initializes the select in the HTML:
<select id="e1" style="width:300px">
<option value="5">Other Value</option>
<option value="4">some value</option>
</select>
You can see that when the select2 initializes and you call the data function, the 2nd option will be selected.
Upvotes: 1