EnterAsTab.js

I was creating a mobile website and pressing enter on my iPad keyboard kept submitting the form.

Here’s the short script I wrote to avoid that problem It’s EnterAsTab.js. It’s pure JavaScript (no jQuery or anything) so there’s no dependencies, although you could use jQuery to refine which elements have the function applied.

EnterAsTab is on GitHub

function enterAsTab(e){
if ( e.which == 13 ) {
        // We’re on a submit, so click it
        if(this.getAttribute(‘type’).toLowerCase() == ‘submit’){
            return; // let default bubble up
        }
        var n,t;
        n = this;
        do {
            n = n.nextSibling;
            if(n === null){ return; }// no next sibling. Do default behavior
            if(n.tagName != “INPUT”){ continue; }
            // don’t deal with things without a type (such as labels or text nodes) or which are hidden
            t = n.getAttribute(‘type’);
            if(t === null || t.toLowerCase() == ‘hidden’){
                continue;
            }
            if(t.toLowerCase() == ‘submit’){
                return; // bubble up to default
            }else{
                n.focus(); // Found one. Focus,prevent default and done
                e.preventDefault();
                return;
            }
        } while(n !== null);
}
}
function applyEnterAsTab(){
    var inputs = document.getElementsByTagName(‘input’);
    for(var i = 0;i<inputs.length;i++){
        inputs[i].onkeypress=enterAsTab;
    }
}

Usage

You can apply it to all <input> field by simply running:

applyEnterAsTab(); // all input elements are now set to use EnterAsTab

If you’ve got jQuery or Zepto already you can do something like:

$('input.enterastab').on('keypress',enterAsTab); // Only the inputs with enterastab class

$("#oneform input").on('keypress',enterAsTab);   // All inputs within a specific form

This entry was posted in Computers, GitHub, Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *