srihari
srihari

Reputation: 437

how to enable arrow keys in javascript

In my application i wrote java script validation for a text field (user name). So it allows only alphabets, spaces, back-space and arrows to move previous and next alphabets in the text field. my code is working fine in the mozila firefox but coming to chrome and IE its not allowing arrow keys.

My code is like this..

<input class="form-control input-lg" onkeypress="return isCharacterKey(event)" onkeyup="capitalize(this)" id="firstNameSpaceCapital"/>

//This function allows space,backspace,alphabets and arrow keys
function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    return false;
}

//This method is used to capitalize the first letter in the text field
function capitalize(obj) {
    obj.value = obj.value.charAt(0).toUpperCase() + obj.value.slice(1);
}

//This method is used to capitalize the first letter after space
$('#firstNameSpaceCapital').on('keyup', function () {
    $(this).val(function (i, val) {
        return val.replace(/(\s)(\S)/g, function ($0, $1, $2) {
            return $1 + $2.toUpperCase();
        });
    });
});

Upvotes: 0

Views: 1827

Answers (3)

webkit
webkit

Reputation: 3369

I'd tackle your issue like this:

Notice for the capitalization only css is needed (for the case you presented at least)

FIDDLE

html

<input class="form-control input-lg" id="firstNameSpaceCapital" />

css

.input-lg {text-transform:capitalize;}

js

$('#firstNameSpaceCapital').on('keypress', isCharacterKey);

function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    evt.preventDefault();
}

good luck!

Upvotes: 1

user3917789
user3917789

Reputation: 90

I think it's a bad idea to catch keyboard events. 'Cause user can paste some text using mouse. So, I'd recommend to use oninput event

Upvotes: 0

m1k1o
m1k1o

Reputation: 2364

return isCharacterKey(event)

event is undefined, use this instead.

return isCharacterKey(this)

Upvotes: 0

Related Questions