I have dropdown using select2 as follows:
<select class=".select2" id="sel">
<option value="1">Some Text</option>
<option value="2">Other Text</option>
<option value="3">best Text</option>
</select>
What I need to make default selection as a particular option , suppose it is second option so I do as follows:
$("#sel").select2("val","2");
It is working fine. What I need is I want to make the option selected only by using the text value, ie, something like that
$("#sel").select2("text","Other Text");
please check fiddle: FIDDLE
Please guide me how can I achieve this without using value and only text of option?
To trigger a change in value, append .trigger("change")
to your script as below.
$("#sel option:contains(Other Text)").attr('selected', true).trigger("change");
or just append .change()
$("#sel option:contains(Other Text)").attr('selected', true).change();
$(function () {
var selectedText = 'Other Text';
$('#sel option').map(function () {
if ($(this).text() == selectedText) return this;
}).attr('selected', 'selected');
});
you can change value using MVC model variable string `
function changeunloadingArea()
{
let $element = $("#unloadingareaselectlists");
let val = $element.find("option:contains(@Model.UnloadingArea)").val();
$element.val(val).trigger('change.select2');
};
`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.