Systems Rebooter
Systems Rebooter

Reputation: 1409

Update <input> value onchange

I have bunch of inputs like:

<input />
<input />
<input />

and a button which ads extra input

<button>Add Input</button>

The issue is that when a user put the text in the input(s) and add additional input afterwards (i.e. press Add Input) the entered text in old inputs disappears.

JSFiddle:

<div id="inputs"></div>

<button onclick="document.getElementById('inputs').innerHTML += '<input /><br>'">Add Input</button>


So I decided to update <input> value attribute. I have tried with onchange but had no luck.

The code with errors and trials is super simple and looks like:

function change_value(el) {

 document.getElementById('some-id').value = el.value
}
<input id="some-id" value="${this.value}" onchange="change_value(this)" />

Will be grateful for any suggestions about how to keep <input value up-to-date with user text.

Upvotes: 0

Views: 1905

Answers (3)

muka.gergely
muka.gergely

Reputation: 8329

It depends on what content you want to update. You can find a snippet below, that works oninput and updates the textContent of a span.

const input = document.getElementById('some-id')
const display = document.getElementById('updated')

input.addEventListener('input', function(e) {
  display.textContent = this.value

})
<input id="some-id" value="" /><br /><br />
<div>Updated value: <span id="updated"></span></div>

EDIT

A new snippet may clear things up a bit.

const btnAdd = document.getElementById('add')

btnAdd.addEventListener('click', function(e) {
  var input = document.createElement('input');
  input.type = "text";

  document.getElementById('inputs').appendChild(input)
})
<div id="inputs"></div>

<button id="add">Add Input</button>

Use createElement() instead of innerHTML.

Upvotes: 2

Hadi R.
Hadi R.

Reputation: 413

Actually, it is not possible this way, maybe with some tricks like with any change store the value and create new input with the new value or change the innerHtml, maybe it works.

Upvotes: 0

Sandeep Amarnath
Sandeep Amarnath

Reputation: 6966

Try using innerHtml like this

document.getElementById('some-id').innerHtml instead of value

https://www.w3schools.com/js/js_htmldom_html.asp

Upvotes: 0

Related Questions