Extract content from an HTML form within a specific cell using Cheerio

A sample HTML table is displayed below:

<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>

The goal is to extract the value of the hidden input named id_num. (For this illustration, the expected value is "ABCD123").

An attempt was made to parse the code using cheerio as showcased here:

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() //Results in an empty string (""). The desired output should be "ABCD123"
    };
});

However, only the first value is correctly retrieved.

Is there a way to obtain the value from the hidden input element id_num?

Appreciate any assistance provided.

Answer №1

It is recommended to use the following syntax:

$(tr).find('[name="id_num"]').attr('value')

Answer №2

This code snippet helps you target specific elements within a table row (<tr>) using jQuery:

$('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()
      };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to eliminate an invalid element from the DOM?

Below is the code snippet showing the xpaths where the value of $value can be found. We have noticed an abnormal tag td1 in the given URL (visible in the image) which is missing a closing tag. It seems like the developers intentionally placed it there, as ...

"Troubleshooting the slow loading of PDF files when using React's render-pdf feature

After creating a table with the ability for each row to generate and download a PDF using render-pdf npm, I encountered an issue. When the user clicks the download button, the PDF preview opens on a new page. However, there are problems with rendering as a ...

Using a custom jQuery function within an Angular component class

I have a custom query function that I wrote in a JavaScript file located under the source folder (/src/assets/inlineedit.js) of my Angular application. Here is the content of the file: $.fn.inlineEdit = function(replaceWith, connectWith) { $(this).ho ...

The importance of using private mode in Nightwatch Internet Explorer

Inside my nightwatch.conf.js, I have the following configuration: "desiredCapabilities": { "browserName": "internet explorer", "javascriptEnabled": true, "acceptSslCerts": true, }, What is the s ...

Issue encountered while attempting to generate a Jquery button

I seem to be facing some difficulties as I have successfully completed this task before. Currently, I am dynamically adding HTML code: ...<td><label><input type=\"checkbox\" checked=\"checked\" class=\"Activechk fo ...

I am seeking guidance on how to update the HTML content being viewed in the browser when a user changes the selected option within a <select> element in ASP.NET

Hello, I'm just starting to learn about web development and ASP.Net. Can anyone help me figure out how to dynamically change the HTML content displayed in the browser when the user selects a different option from a <select> element? @*DropDown: ...

Tips on how to decorate a radio button using borders and colors

How can I change the color of my radio button and its border color? I attempted to modify the code below, but it is not producing the desired result. li.payment_method_bacs input[type='radio']:checked:before { background: black !important ...

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Using SetInterval function in conjunction with jQuery's .each() method

I'm looking to cycle through a group of divs and perform random actions at various intervals. I'm trying to use the function below, but the console.log always returns the same object and integer for each iteration. What would be the correct way t ...

Encountering Gyp Errors During NPM Install in an Angular 5 Project

I encountered some gyp errors when trying to run "npm install" in my Angular 5 project. I'm not sure why these errors are occurring; perhaps someone here has seen similar issues before. https://i.stack.imgur.com/mMRO4.png I attempted various trouble ...

Guide to managing and responding to errors within an API utilizing NodeJS and Express

Currently, I am developing an API using NodeJS with the express framework and mongodb to manage my data storage. The register function that I have performs three main tasks: Creates a new user account. Generates a token and links it to the user. Sends a ...

Guide on implementing csurf middleware with tsoa express

As a beginner in Tsoa, I am looking to incorporate CSRF implementation into my Node app. While I have managed to create APIs using app.use(), I would like to know if there is a way to achieve this using Tsoa. ...

What could be causing the 404 error I'm receiving for this specific URL?

Can someone explain why I keep encountering a 404 error when I type \book into the URL bar? Below is the code I am currently using: var express = require('express'), app = express(), chalk = require('chalk'), debug = ...

What is the correct way to activate buttons within a v-for loop in Vue.js?

My current situation is as follows: https://plnkr.co/edit/LdbVJCuy3oojfyOa2MS7 I am looking to activate the "Press me" buttons when the input changes. At this point, I have a code snippet that can detect when the input has changed: enableButton:functio ...

What is the best way to place text side by side with an image?

How can I align text below a picture like this? https://i.stack.imgur.com/WcNRa.jpg Here is the code snippet: https://jsfiddle.net/vzjj9eLy/ HTML: <span class="test"> <img src="http://cdn.sstatic.net/Sites/stackoverflow/img/<a href="/cd ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Receiving a 404 error when attempting to update row values using an id with sequelize

Currently, I am working on a project using nodeJS, expressJS and reactJS. While I can access each data's id by clicking the edit button, I am facing issues with updating the data. Every time I click the button, a 404 error is displayed in the console. ...

Encountering an error message of "ReferenceError: jQuery is not defined" while attempting to install a package on npm

I recently released a jRCarousel jQuery plugin on npm. Originally, I encountered an error stating that the name cannot contain capital letters. I addressed this by modifying the package.json file and successfully published it. However, when attempting to u ...