-1

for reasons i can't go into too much details with here i have an id that could look like this:

1%20

The reason i have this is because im matching a table of alot of data.

1 means the table row 20 is the list it is in (from the database).

Now i have the following javascript code:

function getSplitId(id) {
    return id.split('%');
}

Which works fine when i do the following:

selected_row_id = getSplitId($(this).get(0).id)[0];

Now i want to get the HTML id of the row ive clicked and for that i have the following code:

rowHtmlId = $(this).id;

Which also works fine however when i need to start using the rowHtmlId to something like for instance:

newElement = $('#' + rowHtmlId).prev();

I get the following error:

Syntax error, unrecognized expression: #44%24

So my question is how can i go around this?

Kevin Brechbühl
  • 4,717
  • 3
  • 24
  • 47
Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

2 Answers2

2

If you have a look at the jQuery documentation, you see

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^{|}~` ) as a literal part of a name, it must be escaped with with two backslashes: \\.

% is a meta character so you have to escape it first:

newElement = $('#' + rowHtmlId.replace('%', '\\%')).prev();

Or you simply use getElementById:

$(document.getElementById(rowHtmlId)).prev();

Or even better (depending on the context), just keep a reference to the row element itself:

var row = $(this);
// ... later
newElement = row.prev();

There is no need to query for it again if you already have a reference to it.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
-2

Just add a backslash to escape the percent sign:

id.split('\%');

in getSplitId() change from:

return id.split('%');

to

return id.split('\%');
lorinpa
  • 556
  • 1
  • 5
  • 6
  • Even though im happy for the response i don't see how this helps me? i dont wish to split the id just select and use it later? – Marc Rasmussen Feb 15 '14 at 19:32
  • Please edit the title of your post :) I answered the question in your title :) Sounds like you have many questions. Good Luck :) – lorinpa Feb 15 '14 at 19:38
  • 1
    This does not even solve the problem mentioned in the title, because `'%'` with `split` doesn't generate such an error: http://jsfiddle.net/nGYy7/. FYI, in JavaScript, the strings `'\%'` and `'%'` are 100% identical. Compare `console.log('\%')` vs `console.log('%')`. – Felix Kling Feb 15 '14 at 19:46