使用' name'的多个select2元素的jQuery选择器属性标签

时间:2016-10-25 21:46:11

标签: javascript jquery twitter-bootstrap select2

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

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

编辑:如果genres返回[]而没有<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>

HTML

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

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

JS

{{1}}

我是如何通过jquery选择器选择输入元素的?

2 个答案:

答案 0 :(得分:0)

您可以使用属性以选择器开头

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?

答案 1 :(得分:0)

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

开头

完整说明https://api.jquery.com/category/selectors/attribute-selectors/