【问题标题】:jQuery selector for multiple select2 element using 'name' attribute tag使用'name'属性标签的多个select2元素的jQuery选择器
【发布时间】:2016-10-25 21:46:10
【问题描述】:

我试图在我的表单上输出各种输入和选择元素的验证错误。但我似乎无法使用类/属性选择器获取元素。 我使用引导程序中的 form-contorl 类来识别所有输入,并使用 select2 插件来修复选择框。

这适用于标准输入框和选择框,但是对于需要在名称属性末尾带有“[]”的多个选择框,它会失败并返回一个空的 jquery 对象。

编辑:顺便说一句,eKey 返回 genres 而没有 []

HTML

<select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true">
    <option value="1">RPG</option>
    <option value="2">FPS</option>
    <option value="3">MMO</option>
</select>

JS

$.each(errors, function (eKey, messages){

    var $input = $('.form-control[name=' + eKey + ']');
    //do stuff with error messages (bootstrap popovers)
});

任何想法如何通过 jquery 选择器选择输入元素?

【问题讨论】:

    标签: javascript jquery twitter-bootstrap select2


    【解决方案1】:

    你可以使用以选择器开头的属性

    var eKey = "genres";
    var $input = $('.form-control[name^=' + eKey + ']');
    console.log($input[0].name);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true">
        <option value="1">RPG</option>
        <option value="2">FPS</option>
        <option value="3">MMO</option>
    </select>

    或转义选择器字符串

    var eKey = "genres\\[\\]";
    var $input = $('.form-control[name=' + eKey + ']');
    console.log($input[0].name);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true">
        <option value="1">RPG</option>
        <option value="2">FPS</option>
        <option value="3">MMO</option>
    </select>

    在 jQuery 版本 3+

    var eKey = $.escapeSelector("genres[]");
    var $input = $('.form-control[name=' + eKey + ']');
    console.log($input[0].name);
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
    <select id="genre-select" class="form-control select2-hidden-accessible" multiple="" name="genres[]" tabindex="-1" aria-hidden="true">
        <option value="1">RPG</option>
        <option value="2">FPS</option>
        <option value="3">MMO</option>
    </select>

    另见Why can't jQuery 3 identify the '#' character in an attribute selector?

    【讨论】:

    • 哇及时回复,有很多选择,谢谢。我以前没有尝试过这些选项中的任何一个。开始选择器似乎是最好的解决方案,因为每次检查都修改“eKey”会很尴尬。
    【解决方案2】:

    您可以尝试在属性值中使用不同的搜索算法,例如属性以选择器开头 - $(".form-control[name^='genres']")

    完整描述https://api.jquery.com/category/selectors/attribute-selectors/

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 2011-10-21
      • 2010-11-02
      相关资源
      最近更新 更多