使用文本而非值设置select2选项 [英] set select2 option using text not value
本文介绍了使用文本而非值设置select2选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我是否具有select2并想设置其中一个选项,我可以运行此代码.
I know if i have a select2 and i want to set one of the options, i can do run this code.
$(document).ready(function(){
$('#btn').change(function(){
$('#select').val(4).trigger("change")
});
});
让我说我想获得选项的文本
Lets say i want to get the text of the option
<option value=4>California</option>
但是如果我想基于文本而不是值进行设置,我该怎么做?
but if i want to set it based on the text not the value, how do i do it?
我尝试做
$("#select").select2(data.text(), "California");
但是没用.
我该如何在jquery或javascript中以编程方式执行此操作.
How can i do this programatically in jquery or javascript.
感谢您的帮助
推荐答案
例如:如果您需要在其他国家中查找澳大利亚
For example: If you need to find Australia among other countries
let long_name = 'Australia';
let $element = $('.country-js')
let val = $element.find("option:contains('"+long_name+"')").val()
$element.val(val).trigger('change.select2');
其他答案对我不起作用,可能是因为我使用的是select2的较新版本
Other answers did not work for me, probably because I use newer version of select2
这篇关于使用文本而非值设置select2选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文