cppit
cppit

Reputation: 4564

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

Upvotes: 0

Views: 315

Answers (5)

Michal
Michal

Reputation: 13639

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;

    }

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108500

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/

Upvotes: 1

Liam
Liam

Reputation: 2837

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

Upvotes: 0

alex
alex

Reputation: 490183

Prevent the default action of the form.

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

Upvotes: 0

Bojangles
Bojangles

Reputation: 101473

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.

Upvotes: 1

Related Questions