0

I have a name input checker using Javascript and I'm struggling to see the issue. When the input has been entered and matches the array, the site should return ("Welcome" . inputValue) as an alert. However, I am getting an alert but it only says "undefined". If the person types in the incorrect name (doesn't match the array) it does feedback "User not know" As it is meant to. So the only issue is when the input value matches the array it gives the result "undefined".

var x = ["Bob", "James", "Alan", "Emilie", "Donna", "Ashleigh", "Arthur", "John"];


function checkInput() {

  var inputValue = document.getElementById("inputString").value;

  var test = x.indexOf(inputValue);

  if (test >= 0)
    alert("Welcome ".inputValue);

  else
    alert("User not known");

}
<form>
  <input type="text" id="inputString">

  <button onclick="checkInput()">Evaluate input</button>
</form>

1
  • 5
    JavaScript is not PHP; the string-concatenation is the + operator, not the period (.). Commented Oct 13, 2020 at 16:04

1 Answer 1

1

The message format on alert function when matched is invalid.

It is needed to "Welcome " + inputValue instead of "Welcome ".inputValue. On javascript, to join string, + operator is used.

var x = ["Bob", "James", "Alan", "Emilie", "Donna", "Ashleigh", "Arthur", "John"];

function checkInput(event) {
  var inputValue = document.getElementById("inputString").value;
  var test = x.indexOf(inputValue);
  if (test >= 0)
    alert("Welcome " + inputValue);
  else
    alert("User not known");
}
<form>
  <input type="text" id="inputString">

  <button onclick="checkInput(event)">Evaluate input</button>
</form>

Sign up to request clarification or add additional context in comments.

1 Comment

Just for the record, "Welcome ".inputValue is syntactically valid: it's reading the property inputValue on the string object "Welcome ", which is undefined (hence no error is being thrown, but undefined is alerted).

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.