jQuery on keyboard backspace move to previous input field if becomes empty

David picture David · Dec 20, 2012 · Viewed 8k times · Source

I have this jQuery script:

$(document).ready(function() {
    //Focus the first field on page load
    $(':input:enabled:visible:first').focus();
    //Clear all fields on page load
    $(':input').each(function() {
        this.value = "";
    });
});
//Clear field on focus
$('input').focus(function() {
    this.value = "";
});
//Allow only alphabetical characters in the fields
$(':input').bind("keypress", function(event) {
    if (event.charCode != 0) {
        var regex = new RegExp("^[a-zA-Z]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
        $(this).next('input').focus();
    }
});
//Enumerate submit click on [ENTER]-keypress
$(':input').keypress(function(e) {
    if (e.which == 13) {
        jQuery(this).blur();
        jQuery('#submit').click();
    }
});
//Submit form
$('#submit').click(function() {
    //Show loading image while script is running
    $("#response").html("<img src='../images/loader.gif'>");

    //POST fields as array
    function serealizeInputs(input) {
        var array = [];
        input.each(function() {
            array.push($(this).val())
        });
        return array;
    }

    var letters = serealizeInputs($('.letters'));

    $.post('loadwords.php', {
        letters: letters
    }, function(data) {
        //Show the resonse from loadwords.php
        $("#response").html(data);
    });
});

See http://jsfiddle.net/8S2x3/1/

I would like to optimze it a little but I don't know how.

Most of the code is copy-paste-modify since i'm still learning

My question(s): How can I move focus to previous textfield on Backspace keypress? I would like to be able to erase the character if you mistype, but if you press backspace again move focus to previous input field. So basically if input is ='' and backspace is pressed, move to previous field. If input has value, and backspace is pressed, act as normal (erase the character)

Also I wonder how to add css class if the field has value in it, and if it's empty add another css class.

Answer

Alfero Chingono picture Alfero Chingono · Dec 20, 2012

Try:

$(':input').keydown(function(e) {
    if ((e.which == 8 || e.which == 46) && $(this).val() =='') {
        $(this).prev('input').focus();
    }
});

Fiddle