Search code examples
javascripthtmlnode.jshtml-tablecheerio

Parse text from HTML form inside table cell with Cheerio


I have a HTML table that looks like this:

<tr class="row-class" role="row">
    <td>Text1</td>
    <td>
        <form method='get' action='http://example.php'> 

            <input type='hidden' name='id_num' value='ABCD123'> <!-- < I NEED THIS VALUE -->

            <button type='submit' class='btn' title='Check' ></button> 
        </form>
    </td>  
</tr>

I want to get the value of the hidden input type named id_num. (In this example the value I want is "ABCD123").

I tried to parse the code with cheerio like this:

var $ = cheerio.load(body);
$('tr').each(function(i, tr){
    var children = $(this).children();

    var x       = children.eq(0);
    var id_num  = children.eq(1);

    var row = {
        "x":        x.text().trim(),     //this is correct, value is Text1
        "id_num":   id_num.text().trim() //This is empty, value is "", I want the value "ABCD123"
    };
});

But I only get the first value correct.

How can I get the value from the hidden input element id_num?

Thanks.


Solution

  • Your eq(1) was getting the whole <tr>, try this instead:

    $('tr').each(function(i, tr){
          var children = $(this).children('td');
          var x        = $(children[0]);
          var id_num   = $(children[1]).find("input[name='id_num']");
          var row = {
              "x":        x.text(),
              "id_num":   id_num.val()
          };
    }