How to add value to an input without removing the value that is already there?

Asked

Viewed 163 times

0

Good afternoon, I’m having trouble finding a way to add value to a readonly input without eliminating the value that’s already in that input. My layout consists of two inputs and a button, the first input is a normal type text input, the second is a readonly input and have an Add button to add the value of the first input to the second it is readonly and I am trying to have the value of the readonly input never deleted by more values that are added. Thank you :)

This is the layout: Este é o layout

This is my script:

function setValue() {
    var nome = document.getElementById('inputNome').value;
    document.getElementById('textNome').value = nome;
};

This is my HTML code:

<div class="form-group col-md-5">
    <label for="inputNome">Nome</label>
    <input type="text" name="inputNome" class="form-control" id="inputNome" placeholder="Nome">
</div>
<button type="button" id="btnNomes" onclick="setValue()" name="btnNomes"class="btn col-md-1 mx-1 px-0 my-auto btn-danger">Add</button> <!--Btn Add-->
<input type="text" class="form-control col-md-5 my-auto" id="textNome" name="textNome" placeholder="Nomes..." readonly /> <!--Readonly Input-->
  • What do you want to do with the value that is already in the input? So you will get a new value right? you want to add these values or separate by virgular? what really you need

  • I would like to separate by comma, I apologize for not being clear in my question

1 answer

1


I used only a validation and concatenation to get the result of a look at the example, if case input2 has no value I assign the value of the first input to the input2, if the input2 I only do the concatenation:

function setValue() {
    var nome = document.getElementById('inputNome').value;
    var input2 = document.getElementById('textNome');
   
    if(input2.value == '' || input2.value == null){
      input2.value = nome;
    }else {
      input2.value += ','+nome;
    }
};
<div class="form-group col-md-5">
    <label for="inputNome">Nome</label>
    <input type="text" name="inputNome" class="form-control" id="inputNome" placeholder="Nome">
</div>
<button type="button" id="btnNomes" onclick="setValue()" name="btnNomes"class="btn col-md-1 mx-1 px-0 my-auto btn-danger">Add</button> <!--Btn Add-->
<input type="text" class="form-control col-md-5 my-auto" id="textNome" name="textNome" placeholder="Nomes..." readonly />

  • It worked very well, thank you very much :)

Browser other questions tagged

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