Nicolas Thery Nicolas Thery - 1 year ago 90
Javascript Question

Migration from jquery1 to jquery 2 : selectors

I'm having troubles with selectors and brackets :

var myInputId = $(input).attr("id")

This is an input id for a checkbox list. I want to select now all the elements having this ID :

$("#" + myInputId);
Uncaught Error: Syntax error, unrecognized expression: #value-5379-32433[]

It works if I escape the brackets but I find this solution quite ugly as I have to use it in many places :

$("#" + inputId.replace("[", "\\[").replace("]", "\\]"))

Do you have a nicer solution to this problem ?

EDIT Note : This has to returns many elements as there is many checkboxes with this ID.

EDIT 2 : The html 3 elements I want to select :

<div class="type_mlist_check ">
<input type="checkbox" id="value-5379-32433[]" value="1" >
<input type="checkbox" id="value-5379-32433[]" value="2" >
<input type="hidden" id="value-5379-32433[]" value="-1">

Answer Source

Since selector contains meta character use attribute equals selector instead.

$('[id="' + myInputId + '"]');

Or use a single String#replace method with character class regex and global modifier.

$('# ' + myInputId.replace(/[#;?%&,.+*~\':"!^$[\]()=>|\/@]/g,'\\$&'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download