首页 > 解决方案 > 获取壁橱的价值select2 jquery

问题描述

我正在尝试closest()从单击保存按钮的位置获取 select2 值.save_entry

我正在尝试获取选择的值,$(this).closest('select').val();但它将返回未定义。我尝试了很多变体,但是因为select2生成了其他 HTML,所以最接近的尝试获取该值似乎存在问题。我在页面上有多个选择,所以我必须使用一个类。

如何获得最近选择的值?

<div class="input-group">
    <select class="form-control select2custom" style="width: 100%">'+data+'</select>
    <span class="input-group-btn">
        <button class="btn btn-primary btn-sm save_entry" type="button" data-id="'+row_id+'">
            <i class="fas fa-check"></i>
        </button>
    </span>
</div>

查询

$(document).on('click', '.save_entry', function() {
    var new_value = $(this).closest('select').val();
})

标签: jqueryjquery-select2

解决方案


closest()仅搜索元素的父元素。选择元素不是按钮的父元素。找到 div,然后找到子选择。

给定您的标记,一种可能的方法是找到最近的输入组,然后找到嵌套的 select2custom 元素,即 select。

$(this).closest('.input-group').find('.select2custom')

推荐阅读