Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
values inside input box become null when i add new input box with javascript

when i add new input box with javascript function, previous input boxes become empty. here is the code:

<div id="field">
    <input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>
<script>
    let i=0;
    const Add=()=>{
        i++
        if(i<5)
        document.getElementById('field').innerHTML+=`<input type="text" id="value${i}">`
        else 
        document.getElementById('error').innerHTML='Error: Field cant be more then 5'
    }
</script>

what can I do to NOT change input values of input box on adding new input box with above codes.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are overwriting the entire HTML content of ID field,

let i = 0;
const Add = () => {
  i++
  if (i < 5) {
    const input = document.createElement('input');
    document.getElementById('field').appendChild(input);
  } else
    document.getElementById('error').innerHTML = 'Error: Field cant be more then 5'
}
<div id="field">
  <input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use Document.createElement() and element.appendChild() so that you do not alter the HTML of the div#field :

<div id="field">
    <input type="text">
</div>
<div id="error"></div>
<button onclick="Add()">add</button>
<script>
    let i=0;
    const Add=()=>{
        i++
        if(i<5) {
          let input = document.createElement("input");
          input.type = "text";
          input.id = "value" + i;
          let button = document.createElement("button");
          button.innerText = "delete";
          button.onclick = function(){
            input.remove(); //remove text input
            this.remove(); //remove this delete button
            i--; //decrement i
          };
          document.getElementById('field').appendChild(input);
          document.getElementById('field').appendChild(button);
        } else {
          document.getElementById('error').innerHTML='Error: Field cant be more then 5';
        }
    }
</script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

One way of doing it, keeping in mind separation of concerns and avoiding the creation of unnecessary global variables could be:

#error {
  display: none;
}
<div id="field">
  <input type="text">
</div>

<div id="error"></div>

<button onclick="Add()">add</button>

<script>
  const Add = () => {
    const inputContainer = document.querySelector('#field'); // this variable is not strictly necessary but I think it makes the code more readable
    const inputNotification = document.querySelector('#error'); // this variable is not strictly necessary but I think it makes the code more readable

    const inputCount = inputContainer.querySelectorAll('input[type=text]').length // count how many input elements of type text are already inside the `field` div

    if (inputCount < 5) {
      const txtInput = document.createElement('input');
      txtInput.setAttribute('type', 'text');
      txtInput.setAttribute('id', `value${inputCount}`);
      inputContainer.append(txtInput);
    } else {
      inputNotification.innerText = 'Error: Field can\'t be more than 5';
      inputNotification.style.display = 'block'
      event.target.setAttribute('disabled', true); // optionally, you can disable the add button if you reached the maximum number of input fields
    }
  }
</script>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda