Abdelouahab Pp
Abdelouahab Pp

Reputation: 4440

How to write on an HTML using an input value?

i want to understand how Javascript works, i'm a user of Tornado (Python) and to put a variable, i use {{variable}}, so i just make:

<h1> {{variable}} </h1>

Now i try to make an HTML edit in a real time, if a user write 1000 for example, there is a somewhere he can see a formatted value, for example 1 000

in javascript, i can get the value from the console using document.getElementById("price").value and then, how do i put in on the HTML code?

Sorry it seems a dumb question.

here is the code:

<input id="price" type="number" name="prix" required title="put here..." placeholder="example: 800000" min="1" step="1">
<script>var val = document.getElementById("price").value;
document.getElementById("ggg").innerHTML = val;</script>`<h1 id="ggg">test</h1>`

Upvotes: 0

Views: 107

Answers (1)

Zeta
Zeta

Reputation: 105886

The simplest way is to modify the .innerHTML attribute of your target element:

var val = document.getElementById("price").value;
document.getElementById("target").innerHTML = val;

You could also modify .textContent.

To do the real time part you have to use an event handler, which gets called whenever the value has changed:

document.getElementById("price").onchange = function(e){
    document.getElementById("target").innerHTML = this.value;
};

Note that change might only fire if the element looses focus. Other events which might be handy are keypress, keydown or keyup, depending on how often you want to update your value.

Upvotes: 2

Related Questions