简体   繁体   中英

Print statement in Javascript (not to console)

I am looking for a way to greet a user when they enter their name using a JavaScript app. The closest I have come is by using:

 function getname() { var number = document.getElementById("fname").value; alert("Hello, " + fname); } 
 <form> Enter name:<input type="text" id="fname" name="fname" /><br/> <input type="button" value="greet" onclick="getname()" /> </form> 

which gives me a pop-up window displaying

Hello, [objectHTMLInputElement]

However, I don't want to use a pop-up window, or even an HTML. I just want JavaScript to greet me using my name after it prompts me to enter one.

You've being using the wrong var inside getname() function...

instead using fname inside alert function you should use number , in my case I changed number to string

 function getname() { var string = document.getElementById("fname").value; alert("Hello, " + string); } 
 <form> Enter name:<input type="text" id="fname" name="fname" /><br/> <input type="button" value="greet" onclick="getname()" /> </form> 

You get [objectHTMLInputElement] because you're alerting fname instead of the variable containing the name ( number ?).

If you want text to speech, you're going to need a library, such as Responsive Voice :

 function getname() { var name = document.getElementById("fname").value; responsiveVoice.speak("Hello, " + name); } 
 <script src='https://code.responsivevoice.org/responsivevoice.js'></script> <form> Enter name:<input type="text" id="fname" name="fname" /><br/> <input type="button" value="greet" onclick="getname()" /> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM