views:

191

answers:

2

I have the following piece of code (Prototype):

$('table_cell_id')

That cell contains a number. How would I get this number into a JavaScript variable?

A: 

If the cell only contains text something like this should do:

var someNumber, stringData = $("table_cell_id").innerHTML.strip();  
if (stringData.length > 0) someNumber = Number(stringData);
if (isNaN(someNumber)) {
  alert("Error: someNumber is not a number");
}
else {
  alert(someNumber);
}

innerHTML returns raw string data of the cell. strip() removes leading and trailing whitespaces and Number(x) casts the trimmed string to a number.

If the cell could be empty you wan't to check for that, of course. Also, it is good to check whether the variable is NaN (not a number).

Here's a one-liner that should work:

var someNumber = Number($("table_cell_id").innerHTML.strip());
Helgi
A: 

See Extending Prototype - getInnerText() for a prototype extension for innerText.

rahul