o_O
o_O

Reputation: 5747

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";
            };
});

Upvotes: 0

Views: 7363

Answers (2)

Bigxiang
Bigxiang

Reputation: 6712

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.

Upvotes: 2

Sukhchain Singh
Sukhchain Singh

Reputation: 41

try with :

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

Upvotes: 1

Related Questions