Archive for the ‘supress form submit’ Tag

Supress form submit in prototype

We’ve got a search field on our site that sits on all pages, when you enter text and hit ‘Go’ it takes you to the search results page.

Recently somebody highlighted a bug whereby hitting the enter key (which is a fairly natural action) submits the form back to itself and not to the search page!

This seems to be a common problem when you may have different actions on a single web form. So here’s a fix using the prototype library:

document.observe('dom:loaded', function() {
	var mybase = new base();
var base = function() {
    var self;

    return {
        init: function(c) {
        isObserved: function(element) {
            return ('_prototypeEventID' in $(element));
        setObservers: function() {
            self = this;
            Event.observe('btnSearch', 'click', this.search_submit);
            Event.observe('txtSearch', 'keypress', this.search_keypress);
        search_keypress: function(e) {
            if (!self.isObserved('form1')) 
                Event.observe('form1', 'submit', function() { return false; });
            var key = window.event ? window.event.keycode : e.which;
            if (key == 13 && $F('txtSearch'))
        search_submit: function() {
            location.href = '/tools_search.aspx?searchterm=' + $F('txtSearch');

Essentially I am observing every keypress on the Search input field, as it means the user is typing in a search term. On the first keypress I hook up an observer to the form’s submit event, which simply returns false when the user hits enter, thus suppressing the submit. The code can then continue and perform the search.