Add values in DIV

Asked

Viewed 56 times

1

Hello

I have 3 inputs, I would like when typing something in input 1, to insert the contents in a result called div, and when typing in input 2 be inserted in the result div and so on, without replacing the previous value in javascript.

Example:

Input 1 - Value: 10

Input 2 - Value: 5

Input 3 - Value: 12

Result in DIV: 10, 5, 12

Thank you

  • Are you using any JS framework or is it pure javascript?

  • Pure Javascript

1 answer

1


Footsteps:

    1. Go through each input and add your value in a array, if it is not empty
    1. Join each item of the array with one ", ";
    1. Write the result in the div
    1. Put everything in one function and run it with the keyup us inputs

var inputs = document.querySelectorAll('.concatenate');
var div = document.querySelector('div');

function fillDiv() { 
  var result = [];
  [].forEach.call(inputs, function(input, i) { // percorrendo inputs
    if (input.value != "") { // verificando se está vazio
      result.push(input.value); // adicionando ao input
    };
  });
  div.innerHTML = result.join(', ') // juntando com o ", " e escrevendo o resultado na div
};

[].forEach.call(inputs, function(input, i) { // adicionando a função ao evento key de cada input
  input.addEventListener('keyup', fillDiv);
});
<input type="text" class="concatenate">
<br>
<input type="text" class="concatenate">
<br>
<input type="text" class="concatenate">
<br>
<input type="text" class="concatenate">
<br>
<input type="text" class="concatenate">
<br>
<br>Resultado:

<div></div>

  • Thanks, but that’s almost what I need, I need that when clicking on the input takes the value and plays in the div;

  • @abduzeedo, I think from what is written in the question, this is serving.

  • ok, how would it look to pick up the value by clicking ?

  • @abduzeedo, put instead of "keyup", "click"

Browser other questions tagged

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