I'm making a website and I'm coming across various issues. Some issues I can solve but (I have to concede) that with the other issues I have no idea what's causing the problem. Hence this thread.
My issue right now is that I simply can't get my If statements to work. They were working before. But then I tried doing a "if the user presses the Enter key, activate the button click function" thing using the code examples at....
W3Schools > Trigger Button Click on Enter
W3Schools > Trigger Button Click on Enter > Try it
And I thought I understood the code. But if that's the case then why aren't my If statements working?
Any help is appreciated!
My issue right now is that I simply can't get my If statements to work. They were working before. But then I tried doing a "if the user presses the Enter key, activate the button click function" thing using the code examples at....
W3Schools > Trigger Button Click on Enter
W3Schools > Trigger Button Click on Enter > Try it
And I thought I understood the code. But if that's the case then why aren't my If statements working?
Any help is appreciated!
HTML:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {font-size: 3em; text-align: center;}
p {font-size: 1.2em; text-align: center;}
#searchbox {display: block; font-size: 1.2em; margin: auto; width: 40%;}
#searchbutton {display: block; margin: 0 auto; width: 5%;}
#resultbox {font-size: 1.2em; display: block; margin: 0 auto; border: 1px solid; min-height: 20em; width: 40%; text-align: justify;}
</style>
</head>
<body>
<h1>Test</h1>
<br>
<input id="searchbox" type="text">
<br><br>
<button id="searchbutton" onclick="showreply()">Ok</button>
<br><br>
<p id="resultbox"></p>
<script>
var x = document.getElementById("searchbox");
x.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("searchbutton").click();
}
});
function showreply() {
alert("Alert."); // Firefox shows 'Alert' which is good.
var y = document.getElementById("searchbox");
alert(y); // Firefox shows an alert window with... "[object HTMLInputElement]";
if (y == "") {
document.getElementById("resultbox").innerHTML = "Please try again.";
document.getElementById("searchbox").focus();
} else if (y == "1") {
document.getElementById("resultbox").innerHTML = "You entered " + x + ".";
}
}
</script>
</body>
</html>
Last edited by a moderator:
