0

I have dynamically generated text type inputs with unique ids (item1, item2, item3, etc) from my html by clicking on the "+" button. I tried to post all the values by using dynamically generated ids by doing $.ajax({ method: 'POST', url:'/addItems', type: 'POST', data: { item: $('#item' + count).val() } however, nothing passes to my data array. I tried with 'item1' instead of 'item' + count and it worked but it's only one value that's already on my html. I also tried to use dataForm or for loops but did not work. Does anyone have an idea of how to pass all values to an array called "items" in my javascript file? for more details, here is my code snippet below (ignore css file. it's for code snippet to run):

const express = require("express");
const app = express();
    app.use(express.urlencoded({extended: true}));
    app.use(express.static("public"));
    app.set("view engine", "ejs");
    app.use(express.json());
    var items = [{item: 'study Node.js'}, {item: 'play Overwatch'}];
    
    app.get('/myForm', (req, res) => res.render("pages/myForm"));
    app.get('/result', (req, res) => res.render("pages/result", {
    items:items}));

    app.post('/addItems', (req, res) => {
        console.log(req.body);
        items.push(req.body);
        res.json({success: 'true'});
        

    });
    app.listen(3000);
h1 {
    grid-area: itemNumber;
    color: white;
    font-family: monospace;
    margin-left: 10px;
    display: inline;
}

input {
    background-color: #DEFDE0; 
    border-radius: 5px; 
    border: 1px solid; 
    outline: none; 
    overflow: auto;
    grid-area: textarea;
    margin-top: 20px;
    width: 150px;
    margin-left: 5px;
}

button {
    grid-area: plus;
    padding: 7px;
    width: 35px;
    border: 1px solid;
    outline: none;
    border-radius: 5px;
    margin-top: 22px;
    margin-left: 5px;
}

#submit {
    background-color: #F0DEFD; 
    border-radius: 5px; 
    border: 1px solid; 
    position: static;
    grid-area: send;
    padding: 7px;
    width: 60px;
}

body {
    background-color: black;

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="myFormStyle.css">
    <title>My Form</title>
</head>
<body>
<!-- Create your form here -->
<div class="container">
    <br/>
    <br/>
    <div class="form-group">
        <form name="add_name" id="add_name" method="post">
            <div class="table table-bordered" id="item_field">
                    <h1>Todo Item 1</h1>
                    <input type="text" name="name[0]" id="item1" class="task" cols="22" rows="2">
                    <button type="button" name="add" id="add" class="addButton">+</button></td>
            </div>
            <input type="button" name="submit" id="submit" value="Submit"/>
        </form>
    </div>
</div>
</body>
</html>
<script>
    $(document).ready(function() {
        var count = 1;
        var $itemIds = Array.from($('h1 + .task'))
        var ids = $itemIds.map(task => $(task).attr('id'))
        $('#add').on('click', function() {
            count++;
            $('#item_field').append('</br><h1>Todo Item ' + count +'</h1><input type="text" name="name['+ (count - 1) +']" id="item'+ count +'" class="task" cols="22" rows="2">');
            $('#add').insertAfter('#item' + count);
        }); 
        $('#submit').on('click', function() {
        $.ajax({
            method: 'POST',
            url:'/addItems',
            type: 'POST',
            data: {
                item: $('#item' + count).val()
            }
        }).
        done(function(data) {
        console.log(data);
        console.log(ids);
        alert(data.success);
        }).
        fail(function(error) {
        console.log(error);
        })
    })       
    });



</script>
  • For starters, you're missing a hash symbol to signify the id: `item: $('item' + count).val()` should be `item: $('#item' + count).val()` – awarrier99 May 12 '20 at 00:14
  • oops, that was a mistake! thank you for catching it. Do you know how to add all my items instead of only the last one? –  May 12 '20 at 00:30
  • No problem, and I just added an answer which should do what you're looking for – awarrier99 May 12 '20 at 00:34

1 Answers1

0

You need to loop through all of the elements to build an array of items containing the values for each item, something like the following snippet.

Note that I left out the ajax part since you can't put Node code in the snippet, so the response in the snippet will be meaningless. The part relevant to your question is the for-loop creating the items array in the script

h1 {
  grid-area: itemNumber;
  color: white;
  font-family: monospace;
  margin-left: 10px;
  display: inline;
}

input {
  background-color: #DEFDE0;
  border-radius: 5px;
  border: 1px solid;
  outline: none;
  overflow: auto;
  grid-area: textarea;
  margin-top: 20px;
  width: 150px;
  margin-left: 5px;
}

button {
  grid-area: plus;
  padding: 7px;
  width: 35px;
  border: 1px solid;
  outline: none;
  border-radius: 5px;
  margin-top: 22px;
  margin-left: 5px;
}

#submit {
  background-color: #F0DEFD;
  border-radius: 5px;
  border: 1px solid;
  position: static;
  grid-area: send;
  padding: 7px;
  width: 60px;
}

body {
  background-color: black;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="myFormStyle.css">
  <title>My Form</title>
</head>

<body>
  <!-- Create your form here -->
  <div class="container">
    <br/>
    <br/>
    <div class="form-group">
      <form name="add_name" id="add_name" method="post">
        <div class="table table-bordered" id="item_field">
          <h1>Todo Item 1</h1>
          <input type="text" name="name[0]" id="item1" class="task" cols="22" rows="2" />
          <button type="button" name="add" id="add" class="addButton">+</button>
        </div>
        <input type="button" name="submit" id="submit" value="Submit" />
      </form>
    </div>
  </div>
  <script>
    $(document).ready(function() {
      var count = 1;
      var $itemIds = Array.from($('h1 + .task'))
      var ids = $itemIds.map(task => $(task).attr('id'))
      $('#add').on('click', function() {
        count++;
        $('#item_field').append('<br><h1>Todo Item ' + count + '</h1><input type="text" name="name[' + (count - 1) + ']" id="item' + count + '" class="task" cols="22" rows="2">');
        $('#add').insertAfter('#item' + count);
      });
      $('#submit').on('click', function() {
        var items = [];
        for (let i = 1; i <= count; i++) { // iterate through all of the items
          items.push($('#item' + i).val());
        }
        console.log(items);
      });
    });
  </script>
</body>
</html>
awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • had to change to items.push($'#item' + i ).val() to get all values from an array. thank you –  May 12 '20 at 02:14
  • @buzzy glad it worked for you, but are you missing a set of parentheses in your comment? That code doesn't look valid (since you're calling `.val` on the return value of `.push` – awarrier99 May 12 '20 at 03:05
  • @buzzy I had made an edit earlier changing this `items.push($('#item' + count).val())` to `items.push($('#item' + i).val())` if that's what you were referring to – awarrier99 May 12 '20 at 03:05
  • yes. that was what I meant. By the way, I have another issue. I need to be able to pass each item in the array separately because each item will be passed to a json array in my javascript. –  May 13 '20 at 05:47
  • Can you elaborate a little on what you mean by that (maybe with some code snippets as well)? It's probably best if you post it as another question and send me the link so we don't have an extended discussion here in the comments – awarrier99 May 13 '20 at 06:24
  • I posted a new question. Here is the link to my new question: https://stackoverflow.com/questions/61785639/how-to-send-each-string-object-in-an-array-as-ajax-post-data –  May 13 '20 at 22:00