Click here to Skip to main content
15,917,174 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get used to javascript DOM.
But I can't figure out the issue.

The function should showing the name I enter with hello, but nomatter what I done, it only show hello, who.

html code:
    <input type="text" placeholder="name" autocomplete="off" onkeyup="full()" id="fname">
 <p id="p"></p>

here is my js code.

var name = document.getElementById("fname");
var p = document.getElementById("p");
              function full(){
                if (name.value) {
                    p.innerHTML = "hello, ${name.value}";
                else {
                    p.innerHTML = "hello, who";

What I have tried:

I changed event from oninput to onkeyup, but got same resulte.

1 solution

The first problem is that you're using a regular string rather than a Template literal[^].

The second problem is that name is a property on the window object. When the event handler function is called, that property hides the name variable. Change your variable to something like fname instead.
const fname = document.getElementById("fname");
const p = document.getElementById("p");

function full() {
    if (fname.value) {
        p.innerHTML = `hello, ${fname.value}`;
    } else {
        p.innerHTML = "hello, who";
Share this answer
nonprocoder 13-Dec-23 12:18pm    
hi, Thank you for your answer, I have fixed the main issue here.
But I have another question would like to ask, it just happened to me.
`hello, ${fname.value}` I don;t know why in my vs code, ${fname.value} is not a value, it's a string, just like hello. I copied your code, it works, but I did on my keyboard, it doesn't work. do you have any idea maybe I made another mistaken?
nonprocoder 13-Dec-23 12:29pm    
But If I change to 'hello, ' + fullname.value, it worked.
nonprocoder 13-Dec-23 12:33pm    
fixed it, i was using Single and double quotes instead of back ticks

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