I'm learning css + js + html rn and while making a simple pop-up message script, i started getting an unexpected string error in the following script:
function myFunction() {
var xbg = prompt("Please enter your name!", "Henry Phillips");
if (person === null || person == "")
{
txt= "Enter your name in the field.";
} else {
txt "Hello" + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
As console says, the string error is specifically located here: line
There is some errors in your script.
First you forget the =
in the else statment.
txt = "Hello " + xbg + "! How are you today?"
----^
The if condition don't test the good variable name, you can replace person by xbg.
if (xbg === null || xbg == "")
// or shorter
if (xbg && xbg.trim())
And finally, you don't call your script another time if user don't enter this name. You can use setTimeout
to give some time to the user for read the message before open prompt another time.
setTimeout(myFunction, 500);
See complete fixed code below
function myFunction() { var xbg = prompt("Please enter your name!", ""); if (xbg === null || xbg == "") { txt = "Enter your name in the field."; setTimeout(myFunction, 500); } else { txt= "Hello " + xbg + "! How are you today?" } document.getElementById("demo").innerHTML = txt; } myFunction();
<span id="demo"></span>
function myFunction() { var person = prompt("Please enter your name!", "Put Your Name"); if (person.trim()) { txt = "Hello, " + person + "! How are you today?" } else { txt = "Enter your name in the field."; } document.getElementById("demo").innerHTML = txt; } myFunction();
<div id="demo"></div>
You can find the edited script here.
so basically you have a typo here: change person with xbg
function myFunction() {
var xbg = prompt("Please enter your name!", "Henry Phillips");
if (xbg === null || xbg == "")
{
txt= "Enter your name in the field.";
} else {
txt ="Hello" + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
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.