Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

validation - jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

What is the best way to restrict "number"-only input for textboxes?

I am looking for something that allows decimal points.

I see a lot of examples. But have yet to decide which one to use.

Update from Praveen Jeganathan

No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9.]/g,'');
});

This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.

You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...