Zagaz
Zagaz

Reputation: 61

Input text via Javascript ECMAscript problem

I'm learning Javascript and I'm trying to input a text in a field, click on a button and change a paragraph innerHTML.

I've already done that successfully. But now I want to make a correction on the field, but when I click the button, nothing happens.

//These are the variables
var name = document.getElementById("name").value;
var bt = document.getElementById("bt");
var para = document.querySelector("p#paragraph");

//event calls the insert().
bt.addEventListener("click", insert);

//The function changes the innerHTML
function insert() {
  para.innerHTML = name;
}
//The textfield to input the name
<input type="text" id="name" placeholder="Your name here"> <br> //The button
<input type="button" value="Click" id="bt"> //The Paragraph to be changed
<p id="paragraph">...</p>

Upvotes: 2

Views: 187

Answers (2)

matthew-e-brown
matthew-e-brown

Reputation: 3007

JS is run when its script tag is loaded by the browser. Your problem is that, when the page loads, you're setting the value of name to the current value of the text field (which is empty when it loads). Move

var name = document.getElementById("name").value;

into the event listener and it should work.


Here is a tidied version:

const name = document.querySelector('#name');
const bt = document.querySelector("#bt");
const para = document.querySelector('p#paragraph');

bt.addEventListener("click", function() {
  para.innerHTML = name.value;
});

// Alternatively, if you don't care for IE
// bt.addEventListener("click", () => para.innerHTML = name.value);
<!-- The textfield to input the name -->
<input type="text" id="name" placeholder="Your name here">
<br />
<input type="button" value="Click" id="bt"> <!-- The button -->
<p id="paragraph">...</p> <!-- The Paragraph to be changed -->

Upvotes: 1

Ananda Masri
Ananda Masri

Reputation: 403

It's not working because your name variable is assigned once at initial script execution before the button is clicked and before the input is filled by the user.

To make it work, move var name = document.getElementById("name").value; inside function insert() so that name is assigned whenever the button is clicked.

Here's a working fiddle.

Upvotes: 1

Related Questions