Chewynugget Chewynugget - 7 months ago 16
HTML Question

If else javascript error

I'm attempting to make a simple code so when you insert your name, it inserts it into the text, but if you don't insert your name it asks you to insert your name. The code seems like it should work, but it doesn't. Can anyone help me?

<body>

<h3>Please enter your name</h3>

<input type="text" id="name" value="" placeholder="Please enter your name">

<p id="dolly"></p>

<button onclick="yourName()">Enter</button>


<script>
function yourName() {
var x = document.getElementById("name").value;
if (x == "") {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
</script>
</body>

Answer
function yourName() {
var x = document.getElementById("name").value;
if (x.length != 0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}