1

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>
2
  • Need x == "" or x === "" Commented Apr 27, 2016 at 2:16
  • 2
    Read your code out loud. If x is equal to an empty string, than display the name, else tell user to enter their name. Next thing, learn to use the developer console in your browser to locate errors, that will get you the syntax issue you have. Commented Apr 27, 2016 at 3:30

3 Answers 3

3
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.";
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

so just to be clear, you were missing the closing curly bracket for the function too.
1

change if (x == "") to if (x != "") and close the function braces.

<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>

Comments

1

Change if(x=="") to if(x!=="" && x.length!==0) and also add a closing brace to close the function. Full code is given below

<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 !== "" && x.length !==0) {
    document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
  } else {
    document.getElementById("dolly").innerHTML = "Please enter your name.";
  }
}
</script>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.