Reputation: 1
I'm learning Javascript, and this basic redirect isn't doing anything.
The alert fires, but no version of 'page redirect' code I've tried seems to be working. I've tried every version of location.href, document.location.href, window.location, etc etc....
I just want to switch urls when user input == '85.5'. But despite hours of trying, it just won't work. What am I missing here? Thanks!
I'm calling this function in a form element like so:
<form onsubmit="showInput()">
<input type="text" id="question" name="inputz">
</form>
function showInput(){
var InputNumber = document.getElementById("question").value;
if(InputNumber == '85.5'){
alert("You escaped"); //this works
alert(InputNumber); //this works
window.location.href ='/Survive_The_Swamp3.html'; //this does NOT work
return false;
}
else {
alert(InputNumber);
document.location.href ="https://i.redd.it/twrza9clfsh21.jpg"; //also doesn't work
return false;
}
}
Upvotes: 0
Views: 805
Reputation: 1
I appreciate the feedback and information from everybody; however the only thing I was able to finally get to work was using the following configuration:
<form onsubmit="showInput(); return false"> //maybe return false here made the difference?
<input type="text" id="question" name="inputz" >
</form>
function showInput(){
var InputNumber = document.getElementById("question").value;
if(InputNumber == '85.5'){
alert("You escaped");
window.location.href='/Survive_The_Swamp3.html';
}
Upvotes: 0
Reputation: 114014
This has nothing to do with window.location.href
.
You don't have anything that submits the form. So the onsubmit
handler is never called.
Forms are submitted when there's an <input type="submit">
which will be rendered as a button. Forms can also be submitted if there's a <button>
inside the form. If neither of these exist then the form is never submitted unless you manually submit the form by calling the form's .submit()
method in javascript.
For your code to trigger you need to wait for the <input>
change event:
<input type="text" id="question" name="inputz" onchange="showInput()">
However there is a subtle issue with how onchange
events work. They are triggered BEFORE the input gets the new value. As such when your user type "85.5"
your event handler will see "85."
. To get the current value you need to read it from the event object:
function showInput(event){
var InputNumber = event.target.value;
//...
The reason onchange
works this way is to allow you to cancel the event thus preventing the <input>
from getting the value. For example you can use this feature to prevent the user from entering something that is not a number.
Upvotes: 1