开发者

JavaScript for (pasting!) only numbers in a textfield

开发者 https://www.devze.com 2023-04-09 18:04 出处:网络
I\'m using this script to have a textfield wit开发者_如何学Ch only numbers, and it works just fine, only my users cant past a number, and as I need 7+ digits, I guess a lot of people will be using cop

I'm using this script to have a textfield wit开发者_如何学Ch only numbers, and it works just fine, only my users cant past a number, and as I need 7+ digits, I guess a lot of people will be using copy paste.

I saw some solutions which use jquery, but seams a bit too heavy for me, and there mus be some light elegant solution which allows pasting?


You can use the number type introduced in HTML5:

<input type="number" min="0" max="9999999">

It’s not supported everywhere, but you can add a fallback for IE using the input.onpropertychange event and check for window.event.propertyName == 'value' inside the handler to listen for any changes in the input field.

For other browsers, you can try the "input" event. Or simply validate and modify on blur to be nicer to the user.

As others have mentioned, it’s considered bad practice to do this as the user types. The number attribute adds a pretty decent way of handling this on it’s own.

0

精彩评论

暂无评论...
验证码 换一张
取 消