Home > Software engineering >  Element created using javascript not appearing in req.body
Element created using javascript not appearing in req.body

Time:11-01

The javascript code used to add rows to a table:

function addRow(tableId) {
          console.log(tableId)
          var table = document.getElementById(tableId);
          var rowCount = table.rows.length;
          var cellCount = table.rows[0].cells.length; 
          var row = table.insertRow(rowCount);
          for(var i =0; i < cellCount; i  ){
              var cell = row.insertCell(i);
              if(i < cellCount-1){
                  cell.innerHTML = '<select  name="list[]">'
                      '<option value="a">a</option>'
                      '<option value="b">b</option>'
                      '</select>'
              }else{
                  cell.innerHTML = '<input  name="listValue[]" type="number" step = "any" value = 0>'
              }
          }
        }

EJS for the original table

<form action="/save" method="post">
  <table  id="table1">
    <tbody>
    <tr>
       <td>
          <select  name="list[]">
             <option value="a">a</option>
             <option value="b">b</option>
          </select>
        </td>
        <td>
            <button type='button'  onclick="addRow('table1')">Add Row</button>          
        </td>
        <td>
            <button type='submit' >Save</button>
        </td>
      </tr>
    </form>
   </tbody>
  </table>

NodeJS server running body-parser and Express

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyParser = require('body-parser');
const open = require('open');
const fs = require('fs');
const prompt = require('prompt-async')
require('dotenv').config();
let cors = require("cors");

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.json())
app.engine('html', require('ejs').renderFile)
app.set('view engine', 'ejs')


//post request
app.post("/save", async (req, res) => {
    console.log(req.body)
})

Without adding a table row, the data comes through perfectly. Once a row is added, that added row's data does not get printed out, only the one originally on the page does. Ex: if first row is selected "a" and a new row is added and selected "b", only value "a" would be printed out.

The result expected is to print out the selected value on every row, instead the data printed is only from the original ejs page and not from the row added using javascript. I've tried manually editing the page using inspect element and no new elements would come through.

Edit: I forgot to mention that the names are arrays. The value of each select option will be stored as an array. Ex if i have row a and b, list[] will contain [a, b]

CodePudding user response:

There is no problem with this code

my actual problem is that I wrapped a form on a nested table <form> element does not send information inside a nested table

  • Related