search

Home  >  Q&A  >  body text

Generate table row by row after user input

When the user enters the page, an HTML table containing two rows will be generated. The first row is the table title, the second row has an input box in the first cell, and the other cells are empty.

Barcode product Amount price
Input box

After the user enters the barcode in the input box, I need:

  1. Update other cells with product details (stored in a MySQL database) based on the inserted barcode;
  2. Generate another line similar to the previous line.

So after the first entry, the form should look like this:

Barcode product Amount price
54573498759384 Pants 10 99 USD
Input box

etc...

I've read everywhere and came to the conclusion that I probably need AJAX, but I've never used it before, so any help is greatly appreciated, just to get started, in the simplest language possible.

I only use PHP and Javascript. I've never used JQuery.

Thanks in advance.

I haven't found a way yet.

P粉674757114P粉674757114265 days ago566

reply all(1)I'll reply

  • P粉990568283

    P粉9905682832024-04-02 17:21:57

    Just add ajax call in onBarcodeChange function to get data from backend

    function onBarcodeChange(id) {
      // ... cal your backend/SQL to get data
      const mockData = {
        product: `Product ${id}`,
        amount: getRandomInt(100),
        price: getRandomInt(10)
      }
    
      const {
        product,
        amount,
        price
      } = mockData
      
      document.getElementById(`product${id}`).innerText = product
      document.getElementById(`amount${id}`).innerText = amount
      document.getElementById(`price${id}`).innerText = price
    
      addTableRow(id + 1)
    }
    
    function addTableRow(id) {
    
      const barcodeInput = document.createElement('input')
      barcodeInput.placeholder = "Enter barcode"
      barcodeInput.onchange = () => onBarcodeChange(id)
    
      // create 4 cells
      const cellNames = ['barcode', 'product', 'amount', 'price']
      const cells = cellNames.map(name => {
        const cell = document.createElement('td')
        cell.id = `${name}${id}`
        return cell
      })
    
      // add input to the 1st cell
      cells[0].appendChild(barcodeInput)
    
      const row = document.createElement('tr')
      cells.forEach(cell => row.appendChild(cell))
    
      const table = document.getElementById('products')
      table.appendChild(row)
    
      barcodeInput.focus()
    }
    
    function getRandomInt(max) {
      const min = 1
      return Math.floor(Math.random() * (max - min) + min);
    }
    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    
    td,
    th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
    }
    barcode product amount price

    reply
    0
  • Cancelreply