2

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>

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 -->

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.