I am trying to sort a table in HTML by clicking the table header. The sorting is fine for strings, but when comparing numbers, it evaluates "10" < "2". Obviously, I'm comparing strings, but I can't get a number out of my table cell. Here's a working example of what's going on:
<script type="text/javascript" >
function sortBy() {
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
var number = rows[1].getElementsByTagName("td")[0].innerHTML;
document.write(number); // This should be printing "7".
}
</script>
<?php
echo "<table id='table'>
<thead><tr><th onclick='sortBy()'>CLICK ME</th></thead></tr>
<tbody><td><input readonly value='7'></td></tbody>";
?>
In this example, I'm trying to get the integer 7. I've tried parseInt(number), but that evaluates to NaN, so I tried writing what number was and it prints a textfield instead of the textfield's content. I've checked this by printing number.length, and I get 29, rather than 1.
I've tried number.value but that's undefined.
I've tried replacing .innerHTML with .value, but that's undefined too.
Is there some way I can convert this into a number? Or at least strip away the html tags and such? I realize I can rig up my own compare logic using the string and it's length ( if (A.length > B.length) { A's bigger } else { compare like normal } ), but that's messy and won't help me to understand this problem.
<input>, NOT the<td>. That's why you get aNaN. You need to append anothergetElementsByTagName(..)[0]to get the input, then you get itsvalueattr.