Javascript 设置第一个选项select2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42703349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:22:33  来源:igfitidea点击:

Set the first option select2

javascriptjqueryselect2

提问by Fabian Sierra

I want to set the first position to select2 dropdown by default, I have tried this but It doens′t work:

默认情况下,我想将第一个位置设置为 select2 下拉列表,我已经尝试过,但它不起作用:

$('#mylist').val($('#mylist option:first-child').val()).trigger('change');

Other way that I tried;

我尝试过的其他方式;

$('#mylist').val(1);

But the problem is I don′t know what value is, because it is depend from a query and It will not always be the same value.

但问题是我不知道值是什么,因为它取决于查询并且它不会总是相同的值。

I did not set the dropdown values ??from the HTML, but it is an input hidden and the values ??are loaded in a query

我没有从 HTML 设置下拉值?

I hope that anyone can help me

我希望任何人都可以帮助我

Regards!

问候!

回答by Seva Kalashnikov

If you using Select2 4.x just trigger change.select2

如果您使用 Select2 4.x 只需触发 change.select2

$('#mylist').val(1).trigger('change.select2');

回答by Muhsinatul F Abas

This works for me:

这对我有用:

$('#mylist option:eq(0)').prop('selected',true);

回答by Alberto FC

please try with this:

请试试这个:

$('#yourSelect2').val($('#yourSelect2 option:eq(1)').val()).trigger('change');

the value from eq()depends of the position that you want to select

eq()的值取决于您要选择的位置

回答by m_callens

It's better to use attribute specifiers and set that element's selectedprop to truelike so:

最好使用属性说明符并将该元素的selectedprop设置为true如下所示:

$('option[value="op2"]').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="list">
  <option value="op1">Option 1</option>
  <option value="op2">Option 2</option>
  <option value="op3">Option 3</option>
  <option value="op4">Option 4</option>
</select>

Then change op2to whatever the valueattribute of the desired default option is.

然后更改op2value所需默认选项的任何属性。

回答by Jaskaran singh Rajal

Please do this

请这样做

$('select#mylist').val(1).select2();