By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Using Javascript/JQuery, how can I read and analyse HTML form data (multi-dimensional array) created by PHP?
JavaScript

Javascript – Using Javascript/JQuery, how can I read and analyse HTML form data (multi-dimensional array) created by PHP?

Admin
Last updated: 2023/12/10 at 1:28 PM
Admin
Share
6 Min Read
Using Javascript/JQuery, how can I read and analyse HTML form data (multi-dimensional array) created by PHP?

Problem:

I’m struggling to read and manipulate data from an HTML form in Javascript/Jquery.

Contents
Problem:Solution:

Context: I have a sales screen showing multiple products, and I want to loop through them all, analyze their contents, and present some of the data in a shopping cart.

Please forgive my lack of knowledge in JS!!

Consider this HTML code (the complete form has a lot more variables for each product, so I’ve simplified it here):

  <input type='text' name='sales[1][qty]' value='10.5' />
  <input type='text' name='sales[1][price]' value='21' />
  <input type='text' name='sales[1][name]' value='Product A' />
  <input type='hidden' name='sales[1][purchaseid]' value='3530' />
  
  <input type='text' name='sales[2][qty]' value='' />
  <input type='text' name='sales[2][price]' value='' />
  <input type='text' name='sales[2][name]' value='Product B' />
  <input type='hidden' name='sales[2][purchaseid]' value='3531' />
  
  <input type='text' name='sales[3][qty]' value='2' />
  <input type='text' name='sales[3][price]' value='10' />
  <input type='text' name='sales[3][name]' value='Product C' />
  <input type='hidden' name='sales[3][purchaseid]' value='3532' />
  
  <input type='text' name='sales[4][qty]' value='' />
  <input type='text' name='sales[4][price]' value='' />
  <input type='text' name='sales[4][name]' value='Product D' />
  <input type='hidden' name='sales[4][purchaseid]' value='3533' />

When someone clicks the Cart button, I want to loop over all entries in the sales[][] array, and display only products whose ‘qty’ or ‘price’ is not blank. The flow would be something like this:

  1. Loop through all sales[][qty] and sales[][price] values. If either is not blank, return the key in sales[].

  2. In the HTML code above, only products sales[1] and sales[3] have these values. So I want to return 1 and 3.

  3. Read the data from those keys and present it in a HTML table. So for example, as only keys 1 and 3 are not blank, I want to read the values of sales[1][qty], sales[1][price], sales[1][name], sales[1][purchaseid] – and the values of sales[3][qty], sales[3][price], sales[3][name], sales[3][purchaseid].

  4. Present them in an HTML table, like below:

     <table>
    <tr>
     <td>ID</td>
     <td>Name</td>
     <td>Quantity</td>
     <td>Price</td>
    </tr>
    <tr>
     <td>3530</td>
     <td>Product A</td>
     <td>10.5</td>
     <td>21</td>
    </tr>
    <tr>
     <td>3532</td>
     <td>Product C</td>
     <td>2</td>
     <td>10</td>
    </tr>
    

I can do this easily in PHP when the form is submitted – but the idea here is to NOT submit the form, meaning JS has to do the job. In PHP I would do it along these lines:

        foreach($_POST['sales'] as $sale) {
        
        $qty = $sale['qty'];
        $price = $sale['price'];
        $name = $sale['name'];
        $purchaseid = $sale['purchaseid'];
        
        if ($qty > 0 || $price > 0) {
            
            $tableRow .= "<tr><td>$purchaseid</td><td>$name</td><td>$qty</td><td>$price</td></tr>";
            
        }
        
    }

I’ve searched and found out how to simply grab names and values from a HTML form by using the below code, but it doesn’t help with my points 2 and 3 above:

    function testCart() {
    
    var str = '';
    var elem = document.getElementById('registerForm').elements;
    
    for(var i = 0; i < elem.length; i++)
    {
                str += "<b>Name:</b>" + elem[i].name + " - ";
                str += "<b>Value:</b>" + elem[i].value + "<br />";
    }
    
    document.getElementById('myCart').innerHTML = str;
    
}

Can someone please give me any pointers on how to proceed with this?

Thank you!

Solution:

One way would be to simply use dynamic attribute selectors in a loop.

We try and find the field with name='sales[1][qty]' first, and if that exists, we check if that value is not empty and read the corresponding other field values for that same index.

I put a simple console.log statement to show the values in the browser console here – that part you will have to replace with actually populating a table with that data.

At the end of the loop we increase the index by one, and try to find the next quantity field in the next iteration. As soon as we don’t find one any more, it is time to break off the loop.

let i = 1;
while (true) {
  let qtyField = document.querySelector('[name="sales[' + i + '][qty]"]');
  if (!qtyField) {
    break;
  }

  let qty = qtyField.value,
    name = document.querySelector('[name="sales[' + i + '][name]"]').value,
    price = document.querySelector('[name="sales[' + i + '][price]"]').value,
    id = document.querySelector('[name="sales[' + i + '][purchaseid]"]').value;
  if (qty != '' || price != '') {

    console.log("Product:", id, name, price, qty);
  }
  ++i;
}
<input type='text' name='sales[1][qty]' value='10.5' />
<input type='text' name='sales[1][price]' value='21' />
<input type='text' name='sales[1][name]' value='Product A' />
<input type='hidden' name='sales[1][purchaseid]' value='3530' />

<input type='text' name='sales[2][qty]' value='' />
<input type='text' name='sales[2][price]' value='1' />
<input type='text' name='sales[2][name]' value='Product B' />
<input type='hidden' name='sales[2][purchaseid]' value='3531' />

<input type='text' name='sales[3][qty]' value='2' />
<input type='text' name='sales[3][price]' value='10' />
<input type='text' name='sales[3][name]' value='Product C' />
<input type='hidden' name='sales[3][purchaseid]' value='3532' />

<input type='text' name='sales[4][qty]' value='' />
<input type='text' name='sales[4][price]' value='' />
<input type='text' name='sales[4][name]' value='Product D' />
<input type='hidden' name='sales[4][purchaseid]' value='3533' />

Expand snippet

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Push elements to array in mongoose while keeping all the other element in the array Javascript – Push elements to array in mongoose while keeping all the other element in the array
Next Article Output all documents in a nested collection Javascript – Output all documents in a nested collection
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?