bewmar
bewmar

Reputation: 3

HTML input number moves cursor off center when typing letters

With an <input type="number"> field that is styled with text-align: center, it works perfectly with numerical input but will move the cursor to the left of the input field if given an alphanumeric character (although it is not displayed).

JsFiddle: http://jsfiddle.net/jbe55o0g/

How can this be prevented such that the cursor remains in the center?

Upvotes: 0

Views: 787

Answers (2)

Rui Cardoso
Rui Cardoso

Reputation: 747

If you are using jQuery, or willing to use, and don't want to be writting that line on all number inputs, you can use the following code:

$(document.body).on('keypress',"input[type='number']", function(event){
    return event.charCode >= 48 && event.charCode <= 57;
})

It will make the same effect as adding the onkeypress attribute, fixing the center issue you were having.

Upvotes: 0

Shady Alset
Shady Alset

Reputation: 5714

When you are using <input type="number"> for numbers only, then you can allow only numeric input using javascript. now the cursor remains in the center :

input[type=number]{
    width: 100px;
    text-align:center;
}
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>

Upvotes: 2

Related Questions