kjarsenal
kjarsenal

Reputation: 934

extract integer from td

if I have a simple html table:

<table>
  <tr>
    <th>header</th>
  </tr>
  <tr>
    <td class="count test">423</td>
  </tr>
</table>

how do I extract the integer from the td so that I can act on it? the following code returns undefined:

function changeCount(){
    var count = $("td.count.test").val();
    alert(count);   
}
changeCount();

complete html:

<html>
 <head>
     <title>Creation of array object in javascript</title>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
     <script language="javascript" >


    function changeCount(){
        var count = $("td.count.test").text();
        console.log(count); 
    }
    changeCount();
    </script>

    <style>
    td{width:200px;text-align:center;}
    </style>
</head>
<body>
<table>
    <tr>
        <th>header</th>
    </tr>
    <tr>
        <td class="count test">423</td>
    </tr>
</table>
</body>
</html>

Upvotes: 0

Views: 2059

Answers (2)

user188654
user188654

Reputation:

The problem is you are trying to access stuff through JavaScript which is not available in the DOM tree at the time your function is executed. You need to make sure changeCount() is fired after the whole DOM tree has been loaded or at least after the element that is required by your function is part of the document DOM tree.

<html>
 <head>
     <title>Creation of array object in javascript</title>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
     <script language="javascript" >


    function changeCount(){
        var count = $("td.count.test").text();
        console.log(count); 
    }
    $(document).ready(function(){
        changeCount();
    });        
    </script>

    <style>
    td{width:200px;text-align:center;}
    </style>
</head>
<body>
<table>
    <tr>
        <th>header</th>
    </tr>
    <tr>
        <td class="count test">four twenty three</td>
    </tr>
</table>
</body>
</html>

Upvotes: 0

Pointy
Pointy

Reputation: 413747

Not .val() for a <td>, but .text().

function changeCount(){
    var count = $("td.count.test").text();
    alert(count);   
}

Note that if there are multiple such <td> elements, that'll return the contents of the first one in the DOM.

The .val() method is for getting the "value" attribute of <input>, <select>, and <textarea> elements. In either case, the DOM access will give you a string. If you need to do computation with the value, then it should be coerced to be a number via parseInt() or one of several other tricks.

Upvotes: 2

Related Questions