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

How can you compartmentalize Express server code from the business logic in Express?

I have noticed that all the Node.js tutorials I've come across tend to put everything in one file. This includes importing libraries, routing, connecting to the database, and starting the server using express.js for example: var app = require('e ...

Ways to switch out error message for an error landing page

I am currently displaying error text when something goes wrong, but I would like to enhance the user experience by redirecting to a well-designed error page instead. Can anyone provide guidance on how to achieve this? Below is my existing code for display ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

Guide to creating a parallax scrolling effect with a background image

My frustration levels have hit an all-time high after spending days attempting to troubleshoot why parallax scrolling isn't functioning for a single image on a website I'm developing. To give you some context, here's the code I've been ...

Is there a way to invoke a function in an iframe from its parent?

How can I call a function that is in an iframe from the parent document? If the function were in the parent, I could simply use parent.func(); but since it's within the iframe, how can I still call it successfully? JavaScript keeps saying it can' ...

What is the best way to center the image on a page?

How can I center an image on the screen with a caption? <div id="team-area"> <div class="container"> <div class="row"> <div class="col-12"> <h3 class="main-title">Our Team</h3> < ...

Is it possible to implement a setInterval on the socket.io function within the componentDidMount or componentDidUpdate methods

I'm currently working on a website where I display the number of online users. However, I've encountered an issue with the online user counter not refreshing automatically. When I open the site in a new tab, the counter increases in the new tab b ...

The functionality to redirect in Wordpress Contact Form 7 based on the value of a radio button selection does

For the past 5 hours, I have been diving deep into Contact Form 7 redirects that are based on values. Despite my efforts, I am unable to figure out why my code isn't functioning properly. Is there anyone who can spot the issue? Contact Form Radio But ...

What is the method for shifting content as the window is resized to ensure it remains in its original position?

My page features a grid with three div elements. Each div is the size of the viewport, resulting in only one div being visible at a time, while the other two remain outside the view. This makes the grid three times larger than the viewport. When resizing ...

When utilizing form-data with the PUT/PATCH method in Node.js and Express.js, the function may return Undefined along with an empty object

After spending the past two days trying various solutions, I am still encountering issues with undefined or {} object when using the PUT and PATCH methods in nodejs Here is a screenshot from Postman index.js [const express = require("express") ...

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...

HTML forms default values preset

I need help with pre-setting the values of a dropdown menu and text box in an HTML form for my iPhone app. When the user taps a button, it opens a webview and I want to preset the dropdown menu and text field. Can someone guide me on how to achieve this? ...

What is the best way to display an error message when a necessary field is left empty?

I am currently utilizing a plugin to validate my form. My goal is to display an error message on the button when clicked, as all fields in my form are required and need validation. Despite attempting the code below, it hasn't been successful: <Fo ...

What could be causing the k8s ingress-nginx to redirect the request elsewhere?

Working with k8s, I have deployed an app running on a clusterIP with port 5270. Now, I am setting up an ingress-nginx to redirect requests to this app. Below is the configuration: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: k8s-ingress ...

Identifying whether a particular area is represented in a geographic map array presents a significant challenge

Having an issue with typescript currently. I have a variable that contains different string entries representing x, y positions. The entries are as follows: ["3,3","3,4","3,5","2,3","2,4","2,5","-1,-2","-2,- 2","-2,-1"] My goal is to determine if this land ...

Received the error 'Headers cannot be set after they have been sent to the client' upon the second request

I created a web server that acts as a client-side application using socket.io-client and express. This setup is necessary for another project I am working on. The web server emits the posted string and responds by sending the served string when it receive ...

retrieving the file name from FormData following an Axios request

I have a question regarding extracting the file name of a WAV file in Node.js. I am sending the file to my backend through Axios using FormData, but I'm unsure how to retrieve the file name. Any assistance would be greatly appreciated. Frontend: //fi ...

Acquire Formik Validation for the Current Year and Beyond

How can I ensure that the input in Formik is restricted to the currentYear and later years only? const currentYear = new Date().getFullYear(); expiryYear: yup .string() .required('Please select an expiry year') .min(4, `Year format must be grea ...

Encountered an error while trying to run NPM install with grunt on Windows

Recently, I attempted to install grunt on my Windows 7 operating system. The process seemed to go smoothly as I successfully executed the npm install -g grunt-cli command without encountering any errors. However, upon trying to run npm install in the root ...