简体   繁体   中英

javascript Redirect submitted form after clicking ok in the alert box

I have a form

onclick confirm , i need to direct it to a particular url

function submitdata() { 
     if(confirm("Are You Sure You Want To Proceed?")) {
        location.replace("http://www.w3schools.com");
    } else { 
        alert("Cancelling"); 
    }

}
</script>

After submitting this form submitdata() is called.

then i am getting an alert.

BUT MY FORM is not getting redirected

<form id="registration_form" action="" method="post" onsubmit="return submitdata();">

        <div id="state"></div>


         <div class="reg-id">
            <label>
                <input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
            </label>

        </div>

        <div class="reg-id">
            <label>
                <input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
            </label>
        </div>

         <div class="reg-id-last">
            <label>
                <input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
            </label>
        </div>
            <input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
        </div>

    </form>
 if(confirm("Are You Sure You Want To Proceed?")) {
    return true; 
    location.replace("http://www.w3schools.com");
 }

return returns from the surrounding function. Nothing after it will be executed. You need to swap the two lines.

I got it

<script>

    function submitdata() { 
       var r = confirm('Are you sure?');

        if (r == true) {

            window.open('http://www.google.com');
        } else {
            alert('it didnt work');
        }
        return false;         

    }
    </script>

If you want the form to actually submit to that location, then the form data won't get sent with that redirect. You can submit the data by setting the action attribute of your form tag to the URL you want, and changing the form submit event to something like this:

function submitData(event) {
  if(confirm('Are you sure you want to proceed?') == false){
    event.preventDefault();
    return false;
  }
}

So instead of redirecting when the user clicks 'ok', you basically just cancel the form submit if the user doesn't click 'ok'.

If you didn't want to submit the data, then you just need to move your return statement, like melpomene suggested.

Note: I always write both event.preventDefault() and return false; but I think usually only return false; would work as well. But, better safe than sorry :)

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