Dana
Dana

Reputation: 19

Can I use the % symbol in javascript or it is considered aspecial character?

I need some help. I need to know if it is possible to use the % symbol in javascript. I ask this question because I have an html table with the following ID= MRRMFBSY_%_CEC. When I try to keep the TD of the second TR of this table the results is undefined, so it seems that it doesnt find the Table with this ID and also when it is defined well. See my code below:

  function getColumnsVal(id) {

    var header = $("table#" + id + " thead tr:eq(1)");
    var header_fields = $("td", header);
    // If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD, 
    // example the firstone it returns undefined
    alert(header_fields[0]);

  }

The question if you think that the problem is the % symbol or not, because when I have the other ID it works perfectly. Thanks in advance

Upvotes: 0

Views: 114

Answers (2)

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

ISSUE:

There is a problem when using certain special symbols %, ^, +, #, and so on, inside a jquery selector. They should be escaped with a backslash(\) when used because they are also used in forming the queries for the selector.

For instance '#divid' is a valid string in JavaScript but would be confusing to use in jQuery if the string was an actual id of an element. To get this element you have to use $('#\#divid').

So, in your case to get your target element, $('#MRRMFBSY_\%_CEC') will get the element easily. However, you can either insert the escape character(\) manually or programmatically as done in this post with regular expression. Therefore, using the square brackets or the native getElementById in this answer, is just another way out of this problem.

You can definitely use % symbol in an id attribute (or in any string) as you would use the dash symbol -. However, you cannot use either of both for JavaScript variable names as they are reserved symbols.

SOLUTION:

Though this question has its own intricacies, @misorude has pointed out a solution here. So there lies your answer. use the square brackets [] or document.getElementById like this.

  function getColumnsVal(id) {
    // var element = $('[id="' + id + '"]'); // this line is equivalent to the next line.
    var element = $(document.getElementById(id));
    var header = element.find($("thead tr:eq(1)"));
    var header_fields = $("td", header);
    // If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD, 
    // example the firstone it returns undefined
    alert(header_fields[0]);

  }

Upvotes: 0

StefanN
StefanN

Reputation: 911

% is a reserved character, since its an operator (see).

It's not recommended, but you can use it as ID in an HTML element.

See this example:

const element = document.getElementById('MRRMFBSY_%_CEC');

console.log(element); // returns the div element
<div id="MRRMFBSY_%_CEC">
  My div with a specific ID
</div>

Upvotes: 1

Related Questions