javascript select2 - 如何使用 jQuery 将值更改为列表的第一个选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32274388/
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-10-28 15:03:59  来源:igfitidea点击:

select2 - How to change the value to the first option of the list with jQuery?

javascriptjqueryjquery-select2

提问by Maxime

I have a form with a select2dropdown.

我有一个带有select2下拉菜单的表单。

The dropdown is in a "modal" window and I want to be able to reset my form when the modal is closed.

下拉菜单位于“模态”窗口中,我希望能够在模态关闭时重置我的表单。

Behaviour wanted: When the modal is opened, I want the default value to be the first option in my select.

想要的行为:当打开模态时,我希望默认值成为我选择中的第一个选项。

<select id="mylist">
    <option value="4">A</option>
    <option value="2">B</option>
    <option value="1">C</option>
    <option value="3">D</option>
</select>

In this case, the selected value would be A(value = 4).

在这种情况下,所选值将是A(value = 4)。

Note that these values are populated dynamically and it cannot be hardcoded.

请注意,这些值是动态填充的,不能硬编码。

My reset function would be:

我的重置功能是:

function reset() {
    $('#mylist').val( /* Code I'm looking for goes here */ );
}

回答by Maxime

Just after I posted my question I found something that was working with select2('val', ...)but it is deprecated in 4.0and will be removed in 4.1.

就在我发布我的问题之后,我发现了一些正在使用的东西,select2('val', ...)但它在 4.0 中已弃用,并将在 4.1 中删除。

The missing part on my end was triggering the changeevent... as I saw in the deprecated documentation. I added it and the event fired the value update!

我最后缺少的部分是触发change事件......正如我在已弃用的文档中看到的那样。我添加了它,事件触发了值更新!

Here is what finally worked:

这是最终有效的方法:

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

回答by Omar Himada

By using the "show.bs.modal" event and the .prop() method in jQuery we can do this easily.

通过使用 jQuery 中的“show.bs.modal”事件和 .prop() 方法,我们可以轻松地做到这一点。

$("#my-modal").on("show.bs.modal", function() {

    $(this).find("select option:eq(0)").prop("selected", true);

});

This would fire every time the modal is opened and because we're using "show.bs.modal" instead of "shown.bs.modal" you shouldn't even see the selection being changed.

这会在每次打开模态时触发,因为我们使用的是“show.bs.modal”而不是“shown.bs.modal”,你甚至不应该看到选择被改变。

回答by Dani

For all select2 in form:

对于表单中的所有 select2:

$('#formId select').each( function( key, value ) {
  $(this).val($(this).find('option:first-child').val()).trigger('change');
});