Javascript Go To A URL If user input a specific nu

2019-09-04 03:39发布

I want if user input on id input-code is only 1234abc, then then he'll be redirected to Google. If he enter anything else, then he'll be redirected to Bing.

My HTML:

<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>

MY Javascript:

    if (document.getElementById('input-code').value == '1234'){
        function btntest_onclick(){
            window.location.href = "http://www.google.com";
        }
        btntest_onclick()
    }else{
        function btntest_onclick(){
            window.location.href = "http://www.bing.com";
        }
        btntest_onclick()
    }

But with this code, when I go to my page, it instantly redirect me to Bing.

1条回答
我只想做你的唯一
2楼-- · 2019-09-04 04:02

You're declaring the same function twice, so it is running the last defined version. And because your code is not in a function or bound to an event it runs on page load. Try this:

function btntest_onclick(){
    if (document.getElementById('input-code').value == '1234') {
        window.location.href = "http://www.google.com";
    } else {
        window.location.href = "http://www.bing.com";
    }
};
查看更多
登录 后发表回答