Orbitall Orbitall - 1 month ago 15
jQuery Question

jQuery selector for multiple select2 element using 'name' attribute tag

Im attempting to output validation errors on various input and select elements on my form. But I cant seem to get the element using a class/attribute selector.
Im using form-contorl class from bootstrap to identify all the inputs and select2 plugin to fix the select boxes.

This works fine with standard input and select boxes, but with a multple select box, which requires '[]' at the end of the name attribute, it fails and returns an empty jquery object.

EDIT: Btw the

eKey
returns
genres
without the
[]
.

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)
});


Any ideas how I can select the input element via a jquery selector?

Answer

You can use attribute begins with selector

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>

or escape selector string

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>

at jQuery version 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>

See also Why can't jQuery 3 identify the '#' character in a selector?