0

I have code that creates a table, each cell of which contains a with an id of row number + "," + column_number (e.g. the top-left cell is built with:

<td><div id="0,0">This is 0,0</div></td>

). I want to be able to modify a cell's contents within the code without having to refresh the entire page, but I can't figure out how to update a particular by ID dynamically. When I do something like this:

var row = 1;
var col = 1;
var newCellContents = "This cell is changed";
var divID = row.toString() + "," + col.toString();
$(divID).html(newCellContents);

it throws a syntax error; I assume it is trying to find a div named "divID".

How would I get it to update the div with ID "1,1"?

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • Where is the syntax error? You've *drastically* changed your code since originally posting the question. – David Apr 24 '17 at 17:46
  • Note that commas may not be valid `id` values: https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – David Apr 24 '17 at 17:47
  • 1
    @David in HTML5 they are valid (in fact anything but a space is valid in an `id`) however the sizzle engine that jQuery uses expects `,` to be a delimiter so they need to be escaped. – Rory McCrossan Apr 24 '17 at 17:48

3 Answers3

2

To achieve this you'll need to escape the comma in the selector, otherwise it will be interpreted as a separator between selectors instead of part of the id value. To do that, precede the comma with \\. You will also need to prepend a # to the selector so that it searches for elements by id. Try this:

var row = 1;
var col = 1;
var newCellContents = "This cell is changed";
var divID = row.toString() + "\\," + col.toString(); // note the use of \\

$('#' + divID).html(newCellContents);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <div id="0,0">This is 0,0</div>
    </td>
    <td>
      <div id="1,1">This is 1,1</div>
    </td>
  </tr>
</table>
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • Got it - put # in front of the id to indicate the variable value is to be used. Also, I changed the separator from "," to "_" and it works without having to escape it. – Don Del Grande Apr 24 '17 at 17:58
0

you have forgottten the # for to access the id

var divID = '#' + row.toString() + "," + col.toString();
Rhea
  • 628
  • 5
  • 12
0

Use a different separator that doesn't require escaping. There are numerous special characters that do

See jQuery selector escaping

Note that concatenating numbers with strings will automatically coerce them to string

var row = 1;
var col = 1;
var newCellContents = "This cell is changed";
var divID = row + "_" + col;
$('#' + divID).html(newCellContents);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="0_0">This is 0,0</div>
<div id="1_1">This is 1,1</div>
charlietfl
  • 164,229
  • 13
  • 110
  • 143