ajmajmajma
ajmajmajma

Reputation: 14226

Escape a variable in jquery

I am trying to pass in a variable as an index to set an active row with a little bit of jquery. I have my variable storing correctly but cannot seem to get jquery to accept the variable in an argument.

Here's what I've got:

$(this).find("td:eq('storeDex')").addClass("activeRow");

storeDex is the variable, If I drop a normal number there it seems to work fine, I'm thinking maybe I need to escape the vaiable some how but I cannot seem to figure out how to do it. Any help would be much appreciated. Thanks!

Upvotes: 2

Views: 1716

Answers (2)

Zack
Zack

Reputation: 2859

From the jQuery :eq selector documentation http://api.jquery.com/eq-selector/

$( "td:eq( 2 )" ).css( "color", "red" );

So I would leave out the single quotes in your example, and the result would look like this:

$(this).find("td:eq(" + storeDex + ")").addClass("activeRow");

Snippet example

var storeDex = 2;
$(function () {
    $("td:eq(" + storeDex + ")").addClass("activeRow");
});
.activeRow {
  background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<table>
  <tr>
    <td>Table cell 1</td>
    <td>Table cell 2</td>
    <td>Table cell 3</td>
    <td>Table cell 4</td>
  </tr>
</table>

Upvotes: 8

James McDonnell
James McDonnell

Reputation: 3710

You need to terminate your string, append the variable and finish your jquery selector with another string.

$(this).find("td:eq('" + storeDex + "')").addClass("activeRow");

Upvotes: 4

Related Questions