简体   繁体   中英

Button click with jquery cancel form and redirect page

http://jsfiddle.net/nqCFL/

I'm trying to check the value of an input and if it's empty, redirect the page, if not empty, redirect to another page. It has no value as is and does not represent what I'm actually trying to do, it is just an experiment. This experiment is supposed to help me with the goal is to check the input and if it's empty, submit the form. If it's not empty, cancel the form and redirect to another page. I'm experimenting with Botcha and this is similar in idea. The problem is the page just continually refreshes on button click and never redirects according to the test I have above.

The experiment I have is:

<form action="" method="post">
    <input type="text" placeholder="issue" class="issue-input" />
    <button class="submit button" type="submit">Send</button>
</form>

$(".submit").click(function(){
            if($(".issue-input").val().length == 0) {
                window.location.href = "http://www.google.com";
            } else {
                window.location.href = "http://www.yahoo.com";
            };
});

Because your button is submit button, so your click will submits the form, try use preventDefault method of jquery.

$(".submit").click(function (e) {
    e.preventDefault();
    if ($(".issue-input").val().length == 0) {
        window.location.href = "http://www.google.com";
    } else {
        window.location.href = "http://www.yahoo.com";
    };
});

try fiddle: http://jsfiddle.net/nqCFL/2/ , I modified the url to an error url, so you can see page is redirected.

try with :

$(".submit").click(function(){
        if($(".issue-input").val() == ''){
            window.location.href = "http://www.google.com";
        } else {
            window.location.href = "http://www.yahoo.com";
        };
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM