Durian Nangka
Durian Nangka

Reputation: 255

Escaping square brackets in element's name when using the Attribute Equals Selector

Please consider the following code:

$('[name='+temp[i][0]+']').prev().addClass('form_error');

where temp[i][0] is an array item holding the name of a form field which contains square brackets (as it represents a checkbox array), name_of_field[].

In order for this to work I know I should escape the square brackets in the form field's name. However, since I'm a newbie to regular expressions, I can't seem to get it right. Could anyone provide me with the proper code? Many thanks.

Upvotes: 0

Views: 1501

Answers (2)

Gordon Rouse
Gordon Rouse

Reputation: 301

I thought I might clarify this, as I will no doubt be going back to this issue again.

The above problem may be best solved with the above 'regular expression' replacement, however, if you are just trying to access a statically named element(s) like below, then here is your simple guide:

<input type="text" name="mytextelement[]" />
<input type="text" name="mytextelement[]" />

<script>
//using vanilla javascript

document.querySelector('[name="mytextelement\[\]"]'); //gets the first element only

document.querySelectorAll('[name="mytextelement\[\]"]'); //gets an array of above elements

//using jQuery

$('[name="mytextelement\[\]"]'); //gets all elements

<script>

Upvotes: 0

Rob W
Rob W

Reputation: 348972

Just quote the value, and escape the quote:

var name = temp[i][0];
name = name.split('"').join('\\"');                   // Escaped " is \\"
$('[name="'+name+'"]').prev().addClass('form_error');

This also accounts for other valid name, but invalid selector characters, such as $.

If you really want to use a RegEx, this following is sufficient (deliberately used a one-liner to show that short code is not always readable):

$('[name="' + temp[i][0].replace(/"/g, '\\"') + '"]').prev().addClass('form_error');
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Upvotes: 3

Related Questions