Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 677
ajmajmajma Avatar asked May 07 '26 20:05

ajmajmajma


2 Answers

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>
like image 61
Zack Avatar answered May 09 '26 08:05

Zack


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

$(this).find("td:eq('" + storeDex + "')").addClass("activeRow");
like image 41
James McDonnell Avatar answered May 09 '26 09:05

James McDonnell