I need to redirect to a link only if the code entered is correct. So the concept is the person inputs a code like 1234 and goes to a.com, but if someone doesnt write that code, they dont go anywhere
I have tried the code below but nothing worked. I change the web names to a.com as the target and b.com as the site redirecting to a.com
<body>
<input type="text" placeholder="Enter Your Code" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Your Code'" maxlength="10" id="input-code">
<p><a href="#" class="btn" onclick="return btntest_onclick()">VERIFY NOW</a></p>
<script>
if (document.getElementById('input-code').value == '1234'){
function btntest_onclick(){
window.location.href = "a.com";
}
btntest_onclick()
}else{
function btntest_onclick(){
window.location.href = "b.com";
}
btntest_onclick()
}
I expect to go to a.com upon giving the code 1234, but it does not happen
You can do something like this:
HTML
<a href="#" class="btn" onclick="btntest_onclick()"></a>
Move your if statement inside the function
JavaScript
function btntest_onclick(){
if (document.getElementById('input-code').value == '1234'){
window.location.href = "a.com";
} else {
window.location.href = "b.com";
}
}
But like I said in the comments, usually you don't check something like this client side because it is easily tampered with.
And you could easily achieve a better solution by setting the href
when the user inputs the correct code.
I would suggest this approach, which avoids using the inline onclick
attribute and uses the more semantic <button>
element instead of a link.
const buttonEl = document.querySelector('.btn'); const inputEl = document.querySelector('#input-code'); buttonEl.addEventListener("click", evt => { if (inputEl.value == '1234') { window.location.href = 'http://a.com'; } });
<input id="input-code" type="text" placeholder="Enter Your Code" maxlength="10"> <p><button class="btn">Verify Now</button></p>
For more info regarding why we try to avoid using onclick
see Why is using onClick() in HTML a bad practice? .
As others have mentioned, this is not a secure way of validating a form and can easily be bypassed by a savvy user. You should use server-side validation if security is a concern for your particular use case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.