How to create HTML form elements with javascript button and functions? and then turn the data into JSON

Asked

Viewed 59 times

-1

I am creating a simple form where after completed will generate the content declaration of the post office and shipping labels automatically, but sometimes there are more than 1 product to be added in the declaration and not to pollute the page thought of having option to register for a product and a button to add more if necessary. It will be more or less like the image below:

inserir a descrição da imagem aqui

The HTML code looks like this:

<h5>Produtos</h5>
<div class="row">
  <div class="input-field col s12">
    <input value="Drinking horn lagarto" id="conteudo1" type="text" class="validate">
    <label class="active" for="first_name2">Produto</label>
  </div>
  <div class="input-field col s3">
    <input value="2" id="quant1" type="text" class="validate">
    <label class="active" for="first_name2">Quantidade</label>
  </div>
<div class="input-field col s3">
  <input value="125.00" id="valor1" type="text" class="validate">
  <label class="active" for="first_name2">Valor unitário</label>
</div>
<div class="row">
  <div class="input-field col s3">
    <input value="1.00" id="peso" type="text" class="validate">
    <label class="active" for="first_name2">Peso total</label>
  </div>
  <a class="waves-effect waves-light btn brown right s3" style="margin-top: 25px;" onclick=""><i class="material-icons left">add</i>Adicionar Produto</a>
</div>

The idea is that by clicking the button Add product he manages another field like this below the first.

Problem 2: Another detail that is breaking my head is how will I mount my object after having the second HTML element? Because my Json is assembled as follows with a single product:

function sendInfo(){

   var remNome = document.getElementById('remNome').value
   var remEndereco = document.getElementById('remEndereco').value
   var remLinha2 = document.getElementById('remLinha2').value
   var remCidade = document.getElementById('remCidade').value
   var remUf = document.getElementById('remUf').value
   var remCep = document.getElementById('remCep').value
   var remDoc = document.getElementById('remDoc').value
   var desNome = document.getElementById('desNome').value
   var desEndereco = document.getElementById('desEndereco').value
   var desLinha2 = document.getElementById('desLinha2').value
   var desCidade = document.getElementById('desCidade').value
   var desUf = document.getElementById('desUf').value
   var desCep = document.getElementById('desCep').value
   var desDoc = document.getElementById('desDoc').value

   var conteudo1 = document.getElementById('conteudo1').value
   var quantidade1 = document.getElementById('quant1').value
   var valor1 = parseInt(document.getElementById('valor1').value)

   var peso = parseInt(document.getElementById('peso').value)

  var pedido = {
    "remNome": remNome,
    "remEndereco": remEndereco,
    "remLinha2": remLinha2,
    "remCidade": remCidade,
    "remUf": remUf,
    "remCep": remCep,
    "remDoc": remDoc,
    "desNome": desNome,
    "desEndereco": desEndereco,
    "desLinha2": desLinha2,
    "desCidade": desCidade,
    "desUf": desUf,
    "desCep": desCep,
    "desDoc": desDoc,
    "itens": [
    {
      "conteudo": conteudo1,
      "quant": quantidade1,
      "valor": valor1
    }
    ],
    "peso": peso
  };

1 answer

-2


Peterson,

To create the elements dynamically with Javascript, you can use the code snippet below. I made some modifications to add a data-attribute as well. It is good practice to work with data-Attributes to isolate code related to screen manipulation and code related to css styling (such as classes).

To learn more:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

var productNumber = 1

function addRow() {
    let newRow = `    
    <div class="row" data-produto="${productNumber}">
        <div class="input-field col s12">
            <input value="Drinking horn lagarto" data-conteudo="${productNumber}" type="text" class="validate">
            <label class="active" for="first_name2">Produto</label>
        </div>
        <div class="input-field col s3">
            <input value="2" data-quantidade="${productNumber}" type="text" class="validate">
            <label class="active" for="first_name2">Quantidade</label>
        </div>
        <div class="input-field col s3">
            <input value="125.00" data-valor="${productNumber}" type="text" class="validate">
            <label class="active" for="first_name2">Valor unitário</label>
        </div>
        <div class="row">
            <div class="input-field col s3">
                <input value="1.00" id="peso" type="text" class="validate">
                <label class="active" for="first_name2">Peso total</label>
            </div>
        </div>
    </div>`
    document.querySelector("body").innerHTML += newRow
    productNumber++;
}

In your HTML, add the "onclick" property by clicking the button, so that the function is executed by clicking the button:

<i class="material-icons left">
   <input id="btnAddRow" type="button" value="Adicionar Produto" onclick="addRow()" />
</i>

When you add more products on the screen, you will add a 'data-product={id}', 'data-quantity={id}', data-value={id}.
This will facilitate the handling of products.

When mounting your object, you can take advantage of the variable productNumber, which already holds the quantity of products added.
That way you can create a loop for from 1 to the amount of products added, and take the data based on the product date, date-quantity, etc..

for(let i = 1; i <= productNumber; i++){
    item = {}
    item.conteudo = document.querySelector(`[data-conteudo="${i}"]`)
    item.quantidade = document.querySelector(`[data-quantidade="${i}"]`)
    item.valor = document.querySelector(`[data-quantidade="${i}"]`)

    //agora adicione esse objeto javascript ao array de itens do seu json
    pedido.itens.push(item)
}

I believe that with just a few adjustments you can implement in your function footpath().
If you’re in trouble, let us know!

  • the first part worked perfectly with small adjustments on the front. The second part that refers to taking product data and assembling my JSON object could not finish. In this I have two problems. 1- There is already a product field before the new ones are created, so when collecting data you need to take what already existed before too. 2 - When I use this function that you showed me in the terminal it prints the whole HTML element. I tried to print something like Console.log(product.valor) etc but without success. Then I don’t know how I’ll mount to the json object either.

  • I edited the original answer, adding a method that should help in solving the second problem!

  • I tried to use his method but for some reason he gives as an undefined request. I tried to put before, after the requested object is declared and still persists. I also tried to add a console.log("item: "+JSON.stringify(item)) to see what was coming before giving the push but it returns all as null. I tried to access pedido.itens and I can usually print on the console. Funny that if I create an item like this: item = {&#xA; "conteudo": "copos",&#xA; "quant": 3,&#xA; "valor": 100.00&#xA; } E add using pedido.itens.push(item) works

  • Just in case someone has the same problem: I was able to solve the problem using Jquery to get the values, so it was done with the same logic of @not_ever that helped a lot. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.