Giorgio Forti
Giorgio Forti

Reputation: 135

How do I select an element with special characters in the ID?

I have a page with a grid containing a lot if input with "strange names" to simulate an array:

 <input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" /> 

How can I set the value of these inputs with jQuery, specifically, how would I select them? I tried in a lot of ways but nothing works.

Upvotes: 3

Views: 6031

Answers (3)

Heretic Monkey
Heretic Monkey

Reputation: 12113

Since this question was asked and answered, more developments have been made in the DOM and CSSOM space to make this easier, both for jQuery users, and for non-jQuery users. I present CSS.escape():

In jQuery:

var id = "Punteggi[@counter].Descrizione";
var selector = `#${CSS.escape(id)}`;
var val = $(selector).val();

console.log(val);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />

Without jQuery:

var id = "Punteggi[@counter].Descrizione";
var selector = `#${CSS.escape(id)}`;
var val = document.querySelector(selector).value;

console.log(val);
<input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />

Upvotes: 0

Andrew Li
Andrew Li

Reputation: 57934

The problem is that brackets have special meaning in CSS (as attribute selectors) and dots do too, as class selectors. Try $.escapeSelector:

$('#' + $.escapeSelector('Punteggi[@counter].Descrizione'))

This will escape the selector so the special characters don't affect the selection. You could also try using an attribute selector and wrapping that in quotes:

$('[id="Punteggi[@counter].Descrizione"]')

This will literally match that ID and won't treat any of the special characters as special characters.

Upvotes: 6

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to escape the [, ], @ and . characters in the id selector. To do that, use \\ like this:

var val = $('#Punteggi\\[\\@counter\\]\\.Descrizione').val();

console.log(val);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />

Upvotes: 3

Related Questions