Home > OS >  jQuery - How to add input while retaining values of previous inputs
jQuery - How to add input while retaining values of previous inputs

Time:11-28

I would like to add new inputs using jQuery, however, after clicking the add input which uses jQuery to add another of such element below, it removes the inputs before.

var num = 2;
document.getElementById('add').addEventListener("click", addInput);

function addInput() {
  var newInput = `
<div>
<input type="date" id="start" name="avail[startdate${num}] value="" min="" max="" />
<input type="range" name = "avail[startdate${num}] value="" min="0" max="23" oninput="this.nextElementSibling.value = this.value" >
<output>12</output><span>:00 (GMT 8) </span>
</div>
`
  // '<input type="text" name="input' num '"/><br> <br>';
  document.getElementById('demo').innerHTML  = newInput;
  num  ;
}
document.querySelectorAll('input[type="range"]').forEach((input) => {
  input.addEventListener('mousedown', () => window.getSelection().removeAllRanges());
});
<p>Availability</p>
<div id="demo">
  <div >
    <input type="date" id="start" name="avail[startdate1]" value="" min="" max="">
    <input type="range" value="" name="avail[startdate1]" min="0" max="23" oninput="this.nextElementSibling.value = this.value">
    <output>12</output><span>:00 (GMT 8) </span>
    <br>
  </div>
</div>
<input type="button" id="add" value="Add input" />

CodePudding user response:

Catch your elements (in example parent). Using insertAdjacentHTML you can append new element on catching element without loosing previous state of range.

Example:

var num = 2;
document.getElementById('add').addEventListener("click", addInput);

function addInput() {
  var parent = document.getElementById('demo');
  var newInput = `
<div>
<input type="date" id="start" name="avail[startdate${num}] value="" min="" max="" />
<input type="range" name = "avail[startdate${num}] value="" min="0" max="23" oninput="this.nextElementSibling.value = this.value" >
<output>12</output><span>:00 (GMT 8) </span>
</div>
`
  // '<input type="text" name="input' num '"/><br> <br>';
  parent.insertAdjacentHTML('beforeend', newInput);
  num  ;
}
document.querySelectorAll('input[type="range"]').forEach((input) => {
  input.addEventListener('mousedown', () => window.getSelection().removeAllRanges());
});
<p>Availability</p>
<div id="demo">
  <div >
    <input type="date" id="start" name="avail[startdate1]" value="" min="" max="">
    <input type="range" value="" name="avail[startdate1]" min="0" max="23" oninput="this.nextElementSibling.value = this.value">
    <output>12</output><span>:00 (GMT 8) </span>
    <br>
  </div>
</div>
<input type="button" id="add" value="Add input" />

CodePudding user response:

By using document.getElementById('demo').innerHTML you are updating the current HTML inside the demo div. you may use another id or instead of innerHTML you may use jQuery append.

  • Related