Gather data from various HTML elements with JavaScript when submitting a form

How can I extract values from HTML elements and send them for processing through a form?

I'm attempting to compile a menu item list with the individual items' structure in place, but I'm struggling to figure out how to fetch the values upon form submission.

It just struck me that my current approach is incorrect as the items are not linked to the form.

What's the proper way to associate elements with the form and capture the values onSubmit?

const form = document.querySelector('#menu-item-form');
form.addEventListener('submit', function() {
  console.log(this.querySelector('.topping').value)
})
.menu-item {
  display: flex;
  position: relative;
  flex-direction: row;
  justify-content: space-between;
  height: 20rem;
  max-height: auto;
  padding: .5rem;
  margin: 2rem auto;
}

.menu-item #menu-item-form {
  display: none;
}

.menu-item .item {
  flex-basis: 50%;
}

.menu-item .price,
.menu-item .topping {
  align-self: center;
  margin-top: 2rem;
}

.menu-item button {
  flex-basis: 20%;
  margin-top: 2rem;
  height: 3.5rem;
  align-self: center;
}

.menu-item .item img {
  object-fit: cover;
  width: 100%;
  height: 80%;
}

.menu-item .item p {
  margin: 0;
  font-family: "Blanch";
  font-size: 5rem;
  color: rgb(34, 33, 33);
}
<li class="menu-item">
  <form id="menu-item-form">
  </form>
  <div class="item">
    <p class="item-name">name</p>      // capture
    <img src="../../assets/img/menu/bbq-chicken pizza.jpg">
  </div>
  <span class="topping">
                <select name="topping" id=""> // capture
                  <option value="">Topping</option>
                  <option value="tomato">Tomato</option>
                  <option value="pepperoni">Pepperoni</option>
                </select>
                </span>
  <span class="price">1350.00</span>    // capture
  <button class="order-btn" form="menu-item-form" type="submit">Add to Order</button>   // submit
</li>

Answer №1

Initially, your HTML code has a mistake. Here is the corrected version:

<li class="menu-item">
    <form id="menu-item-form">
        <div class="item">
            <p class="item-name">name</p> // capture
            <img src="../../assets/img/menu/bbq-chicken pizza.jpg">
        </div>
        <span class="topping">
            <select name="topping" id=""> // capture
                <option value="">Topping</option>
                <option value="tomato">Tomato</option>
                <option value="pepperoni">Pepperoni</option>
            </select>
        </span>
        <span class="price">1350.00</span> // capture
        <button class="order-btn" form="menu-item-form" type="submit">Add to Order</button>
    </form>
</li>

If you are using vanilla Javascript, you can skip using the form tag. Here's an alternative way to achieve it:

My HTML

<li class="menu-item">
    <div id="menu-item-form">
        <div class="item">
            <p class="item-name">name</p> // capture
            <img src="../../assets/img/menu/bbq-chicken pizza.jpg">
        </div>
        <div class="item">
            <input class="field" name="firstname" type="text">
        </div>
        <div class="item">
            <input class="field" name="lastname" type="text">
        </div>
        <div class="item">
            <select class="field" name="topping"> // capture
                <option value="">Topping</option>
                <option value="tomato">Tomato</option>
                <option value="pepperoni">Pepperoni</option>
            </select>
        </div> 
        <button class="btn-send-data" id="send-data" type="submit">Add to Order</button>
    </div>
</li>

My Javascript

function saveData() {
    const myDataForm = document.getElementById('menu-item-form');
    const dataFields = myDataForm.querySelectorAll('[class^="field"]');
    let params = {};
    dataFields.forEach((element) => {
        params[element.name] = element.value
    });
    const request = new XMLHttpRequest();
    request.open('POST', 'http://myexample.com/mywebservice');
    request.setRequestHeader('Content-Type', 'application/json'); 
    request.send(JSON.stringify(params));
} 
const btnSendData= document.getElementsByClassName('btn-send-data');
Object.keys(btnSendData).forEach((key) => {
    btnSendData[key].addEventListener('click', saveData);
});

This example highlights one approach to solving the issue, but there are numerous other methods you could explore.

Answer №2

It is true that the answers provided above are accurate. Fundamentally, when a <form /> element is submitted, any <input /> elements with a defined name attribute contained within it will be included in the submission process.

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

Importing JWT in ES6SyntaxCreating ES6 imports

I'm currently developing a nodeJS web application and utilizing JWT for authentication. My code is all written in ES6 modules, so I wanted to import JWT the same way. However, it seems that the package does not fully support this method yet. Since I&a ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

Issues with data retrieval from PHP file in AJAX submission

During my attempts to utilize AJAX for submitting data to a PHP file, I encountered an issue where the submission was successful and I could receive a message echoed back from the PHP file. However, when trying to echo back the submitted data or confirm if ...

Use ng-repeat to extract information from an array and populate it into a datalist

I've already tried searching for a solution to my issue on Google, but I couldn't find anything that really helped me. I'm looking to create an input field that also functions like a dropdown. This way, I can either type in my own data or se ...

Creating a Unique CSS Grid Border with Custom Images

I have a client project using nextjs and the design calls for a component with a custom border on a responsive CSS grid. I've successfully created the CSS grid with all the necessary content, but I'm struggling to add the required border as per t ...

Can you guide me on where to find the login with Facebook button on this site?

I am currently working on integrating a Facebook authentication system into my app, but I find the default log in button provided by Facebook developers section to be quite unappealing. My Question: I am curious about how websites like Stack Overflow man ...

The efficiency of XSL Template is significantly impacting loading time

Hello there, I am facing a challenge with my webpage's loading speed due to the code provided below. Can you assist me in optimizing it? <xsl:template match="Category" mode="CategorySelectorScript"> <xsl:variable name="ThisCateg ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

There is a space separating the slider image and the navigation bar

Having a small space between the slider image and the navigation bar is causing some issues. I've tried various solutions like minifying the code, adjusting margins, and setting line heights to zero but nothing seems to be working. One question I have ...

When using React / Next.js, the .map() function may not rerender the output based on changes in the state array if the keys remain the same

In my react component, Matches.js, I handle the display of tournament matches sorted by rounds. The data is fetched from a parent component through nextjs SSR and passed as props to the child component. To avoid unnecessary requests upon data changes like ...

Node.js is known for its ability to export both reference and pointer values

Having an issue with exporting my routing table from my express application. In the /bin/www.js file, there is a global variable representing the routing table: var routingTable = []; To create a simple route, new routing objects are pushed using the se ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Guide on transporting PNG files over the boundary

I am working with two specific css commands. code h1 { background: #000000; border-radius: 6px; color: #fff; display: block; font: 40px/60px "Sans", Inconsolata, "Lucida Console", Terminal, "Courier New", Courier; padding: 40px 40px; text-align: center; ...

Customize your Material-UI theme with a unique hover effect for contained buttons

Currently, I am in the process of setting up a theme for Material-Ui on my React application. Within the app, there are two types of buttons that I utilize - contained and outlined. The issue lies with the hover effect on the contained button (while the ou ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

What could be causing the error when attempting to release this Node-MySQL pool?

My first attempt at utilizing connection pooling is with Node.js. I crafted a database connection module in Node.js to establish a single connection, which is then referenced within a pooling function for later use when passed to different modules. /* D ...

What can be done to avoid a form being reset when it returns no results?

I've recently created a mysql and php search page, which is working well. However, I noticed that when the form is submitted and there are no results returned, the <option> tags get reset. Is there a way to prevent this from happening? META: I ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

Mobile Iframe in Full View

Currently, I am working on a small project using Angular and Twitter Bootstrap. However, I have encountered a problem. I am trying to create a template that displays content in full screen upon clicking a button. The issue is that the iframe I am using wor ...

Initiate an AJAX request to the server upon beforeunload event

It seems that starting with Firefox version 4, binding the window jQuery object to beforeunload is no longer effective. I want to send an AJAX post request to delete data from my server's memcache. When I refresh the only open tab, I can observe tha ...