I want to redirect user to different pages depending of what he filled in a input field.
example :
- when he types 1 or 2 he will be redirect to google
- when he types 3 or 4 he will be redirect to facebook
- when he types 5 he will be redirect to stackoverflow
else show a message
CodePudding user response:
Try using the if else
statement and window.location.href
to guide the user to the destination window.
function redirect() {
const inputVal = Number(document.getElementById("inputVal").value);
let url = "";
if (inputVal) {
if (inputVal === 1 || inputVal === 2){
url = "https://www.google.com"
} else if (inputVal === 3 || inputVal === 4){
url = "https://www.facebook.com"
} else {
console.log('Redirect Not Defined!!')
}
}
if (url) {
window.location.href = url
}
}
document.getElementById("redirectButton").addEventListener("click", redirect);
<input type="number" value=1 id="inputVal" />
<button type="button" id="redirectButton"> Redirect </button>
CodePudding user response:
I normally do not recommend the switch statement, but here it is apt
Note that here at SO the action may be blocked
document.getElementById("myForm").addEventListener("submit", function(e) {
let loc = "";
switch ( document.getElementById("inputVal").value) {
case 1:
case 2:
loc = "https://www.google.com";
break;
case 3:
case 4:
loc = "https://www.facebook.com"
break;
case 5:
loc = "https://stackoverflow.com";
break;
default:
console.log('Redirect Not Defined!!')
e.preventDefault(); // cancel submit
}
if (loc) this.action = loc;
})
<form id="myForm" target="_blank">
<input type="number" value=1 id="inputVal" />
<button type="submit"> Redirect </button>
</form>
CodePudding user response:
Here's another viable suggestion using an object as a map referencing desired locations by index:
const EL = (sel, EL) => (EL || document).querySelector(sel);
const navigate = () => {
const addr = [
"google.com",
"facebook.com",
"stackoverflow.com",
];
const maps = {
1: 0,
2: 0,
3: 1,
4: 1,
5: 2,
};
const EL_num = EL("#num");
const url = addr[maps[EL_num.value]];
if (url) return location.assign(`https://${url}`);
console.log("Coudn't navigate");
};
EL("#go").addEventListener("click", navigate);
<input id="num" type="number" value="1">
<button id="go" type="button">Go</button>
much more clean than by using if
or switch
statements.