Reputation: 83
I am creating a "fortune teller" function with one input and one button. The user writes a question and then can click the button for the function to complete. However nothing happens when the user hits enter. I tried a few solutions I found on here, but nothing was working. I do not do a lot of JavaScript. Thank you!
var outcomes = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes - definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don’t count on it",
"No",
"My reply is no",
"My sources say yes",
"Outlook is not so good",
"Yes",
"Yes, it would benefit you",
"Reply hazy, try again",
"Very doubtful",
"Signs point to yes",
"No, it wouldn't benefit you"
];
function ask() {
var x = document.getElementById("input-box").value;
var sel = Math.floor(Math.random() * outcomes.length);
var b8 = outcomes[sel];
if (x.indexOf('?') + 1) {
document.getElementById("answer").innerHTML = b8;
} else {
document.getElementById("answer").innerHTML = "Try with a question mark (?)";
}
}
<div class="ask">
<input id="input-box">
<div class="button" onclick="ask()">
<img src="img/ask-1.png" onmouseover="this.src='img/ask-2.png';" onmouseout="this.src='img/ask-1.png';">
</div>
<p id="answer"></p>
</div>
Upvotes: 0
Views: 185
Reputation: 345
If you put it in a form and add return false
to the onsubmit
(so the form doesn't redirect). It should work.
Code:
<div class="ask">
<form onsubmit="ask(); return false;">
<input id="input-box">
<div class="button" onclick="ask()">
<img src="img/ask-1.png" onmouseover="this.src='img/ask-2.png';" onmouseout="this.src='img/ask-1.png';">
</div>
</form>
<p id="answer"></p>
</div>
Upvotes: 0
Reputation: 256
You can add a keyup
event listener to your input. It should look like this :
<!-- rest of your code -->
<input id="input-box" />
<script>
document.getElementById("input-box").addEventListener("keyup", function(event) {
// 13 in the code of the enter key
if(event.keyCode == 13){
// your function
}
})
</script>
<!-- rest of your code -->
Upvotes: 1