Click here to Skip to main content
15,745,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm learning JS. I'm trying to do a simple task: take the value from an input and then display it in a paragraph. However, when I do that the text flickers and disappears. Why? Also console.log(userName.value) doesn't work either. Please, help.

HTML
<pre> <form>
    <label for="userName"
      >What's your name?
      <input type="text" id="userName" />
    </label>
    <button class="btn">Submit</button>
  </form>
  <p class="demo"></p>




JavaScript
  const userName = document.querySelector("#userName");
  const demo = document.querySelector(".demo");
  const btn = document.querySelector(".btn");

btn.addEventListener("click", function(){
    demo.textContent = "Hello," + userName.value;
    console.log(userName.value);
})


What I have tried:

I tried to change demo.innerHTML but the effect is the same.
It's so frustrating when a simple code doesn't work.
Posted
Updated 19-Oct-22 1:47am
v2
Comments
Member 15627495 19-Oct-22 2:24am    
hello,

with the button tags, the form tag become deprecated.

'form tag' fires a reload/refresh of your web page.

1 solution

As Member 15627495 hinted at in the comments, clicking the button submits the form, which will cause the page to reload and lose any changes made by your script.

You either need to change the button to type="button", or prevent the form from being submitted.

For example:
HTML
<form>
    <label for="userName">
        What's your name?
        <input type="text" id="userName" />
    </label>
    <button type="button" class="btn">Submit</button>
</form>
<p class="demo"></p>
JavaScript
const userName = document.querySelector("#userName");
const demo = document.querySelector(".demo");
const btn = document.querySelector(".btn");

btn.addEventListener("click", e => {
    e.preventDefault();
    demo.textContent = `Hello, ${userName.value}`;
    console.log(userName.value);
});
Demo[^]
 
Share this answer
 
Comments
Tom-learning-to-code 19-Oct-22 13:05pm    
button type=button worked. I wonder why? Is button without type="button" a different kind of a button? In the past I did a similar exercise but I had button onclick=myFunction() and it worked fine.
Richard Deeming 20-Oct-22 4:07am    
If you don't specify a type for the button, the default is submit: <button>&colon; The Button element - HTML&colon; HyperText Markup Language | MDN[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900