Advertisement
Advertisement


Button click with jquery cancel form and redirect page


Question

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";
            };
});
2015/03/17
1
0
3/17/2015 12:53:48 PM

Accepted Answer

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.

2013/09/01
2
9/1/2013 2:31:30 AM

try with :

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