I have made an array with 3 names, and i basically want it so, if someone types in one of the names in the array, i want it to show an alert box, well basically showing that the JS is doing something.
Cheers Guys.
var names = ['Alex', 'Dale', 'Mike'];
var nameSelector = document.getElementById('name-area').value;
function nameGrabber() {
if (nameSelector === names[0]) {
alert("Nice Name bro.");
} else if (nameSelector === names[1]) {
alert("Mate, that's a name that you have.");
} else if (nameSelector === names[3]) {
alert("Ok that's fine.");
} else {
alert("PUT IN ONE OF THE NAMES PLEAZE... thanks :)");
}
}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Javascript Lesson</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="app.js"></script>
</head>
<body>
<input type="text" id="name-area"></input>
<input type="submit" onclick="nameGrabber()"></input>
</body>
</html>
CodePudding user response:
You need to move the nameSelector variable into your submit function, otherwise the value of nameSelector always remains the initial value of the input field (which is empty). Something like:
var names = ['Alex', 'Dale', 'Mike'];
function nameGrabber() {
var nameSelector = document.getElementById('name-area').value;
if (nameSelector === names[0]) {
alert("Nice Name bro.");
} else if (nameSelector === names[1]) {
alert("Mate, that's a name that you have.");
} else if (nameSelector === names[3]) {
alert("Ok that's fine.");
} else {
alert("PUT IN ONE OF THE NAMES PLEAZE... thanks :)");
}
}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Javascript Lesson</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="app.js"></script>
</head>
<body>
<input type="text" id="name-area"></input>
<input type="submit" onclick="nameGrabber()"></input>
</body>
</html>