I’m very new to JavaScript but have worked on HTML from time to time.
I’ve made a text box with a button "Enter" to enter the answer, the problem is I don’t know how to really make the script (since I’m very new to JS). I want to know how to redirect the user to a new page, if
the answer is correct from the text box where they input.
I am also new to this website, so I might not know what to do here to start off with.
Here’s the code:
function submit() {
var bynavn;
if (bynavn == "Vonsild") {
location.href = "/lykkelig.htm"
} else {
location.href = ""
}
document.getElementById('knap').src = enter;
document.getElementById('tekst').src = bynavn;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<title>Niveau 5</title>
<link href="/ZPWSODwhnzO!SJKAzmaPQ/style.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<div>
<img src="hvorervihenne.png" width="1199" height="611" />
<br> Hvor er vi?: <input type="text" id="tekst">
<button onclick id="knap">Enter</button>
<script src="/svar.js"></script>
</div>
</body>
</html>
Help would be very much appreciated.
I’ve tried looking on this website, looking after my issue, but it was in a different coding language and I didn’t want to do that.
2
Answers
Try this code :
There are two steps to doing this:
bynavn
(in your code, it is just left uninitialized), andTo do that first step all you need to use is use
document.getElementById()
to get the input box, then access its.value
property. The.value
property contains the text that is currently in the input box.The second part is also really easy, even though the explanation is a bit much. Just change the
href
property of the globallocation
object. It’s common to write it aswindow.location.href
because to indicate that it is a global variable instead, but sometimes you’ll see it as justlocation.href
too. This is OK because every global variable is a property on thewindow
object.Using both of these steps you get this code:
Note that there as a few more general code improvements you can make:
else
block at all unless you’re going to use it for something later.bynavn
variable to be full lowercase with.toLowerCase()
, then only check it against lowercase strings. This will make the input case insensitive, which might be what you’re looking for.