limit the choices of acceptable inputs using javascript
Is it possible to prevent user f开发者_如何转开发rom writing letters to a textbox (i.e. force user to enter only numbers in textbox) using javascript?
Sure, you put an event handler on keydown events and cancel those for non-digits when the relevant text box has the focus. See element.onkeydown
event.
You can of course do this in vanilla Javascript but like many things, it's easier with a library (like jQuery).
For example, assuming:
<input id="one" type="text">
<input id="two" type="text">
try:
document.getElementById("one").onkeydown = numbers_only;
function numbers_only(evt) {
return evt.keyCode >= 48 && evt.keyCode <= 57;
}
The first should only allow digits.
the exact code that i was looking for is:
$('#id').bind('keypress', function (e) {
return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
});
If you don't fancy writing it from scratch you can use the following jQuery plugin: http://www.itgroup.com.ph/alphanumeric/ and then writing:
$('#id').numeric();
And its been asked before here: how do i block or restrict special characters from input fields with jquery?
ADDITIONAL: And make sure you validate on the server regardless!
$('#input-id').bind('keypress', function(e) {
return !((e.which < 48 || e.which > 57) && e.which != 8 && e.which != 0);
})
If you want to catch this on a submit event then you can use regex to do that in the submit event hanlder.
But if you want to do this when the user interaction with the text box is going on then you will have to manipulate keydown and focus events. By wiring only keypress or keydown events will not prevent the user from entering other characters. He can also drag text into the text box. So focus event will prevent that from happening.
精彩评论