简体   繁体   中英

prevent form from submitting to a different page

I have this code:

<form method="get" action="" id="search">
<input id="search_box" name="search" type="text" class='search_box'  onkeypress="if(event.keyCode==13) sentAjax('searchdata.php');var filelink='searchdata.php';"  value="" onclick="this.value=''" />
        <input type="hidden" name="course_val" id="course_val" />
</form>

I want to block the form from submitting to a different page.Now if you hit enter it submits to a different page

in pure javascript

<form method="get" action="" id="search" onsubmit="return false;">
...
</form>

Please note that will not let you submit the form so ideally you would invoke your submit handler function in which you would control when you want to submit

<form method="get" action="" id="search" onsubmit="return mySubmitHandler()">
...
</form>

and in your submit handler

        function mySubmitHandler(){
        if (submit_criteria_met) {
        return true;
        } else {
        return false;
        }
return false;

    }

This should do the trick:

$('form#search').on('submit', function(e) {
    e.preventDefault();
});

The important part being e.preventDefault() , which prevents the form submitting when it's submit event is triggered.

Remove the onkeypress attribute in the input field, it looks like it does some posting behind the curtains when pressing enter (keycode 13).

You might also want to prevent the form from submitting, although it seems to submit to the same page since the action attribute is empty.

If you are unable to edit the HTML, try something like:

$('#search').submit(function(e) {
  e.preventDefault();
}).find('input[onkeypress]').removeAttr('onkeypress');

Test: http://jsfiddle.net/DAvfm/

$('#search').bind('submit',function(e) {
    e.preventDefault();
});

阻止表单的默认操作。

$('#search').submit(function(event) { event.preventDefault(); });

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