I'm trying to make a date textbox on my blog, and the date is only numbers. I don't want anybody making a mistake typing a letter. Is there any way to limit the characters to only numerals? Thanks!
问题:
回答1:
If you use jQuery, you can do it like in this jsfiddle
$('input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
回答2:
Use HTML5 input number type instead and leverage native browser validation. Thus, no JavaScript required.
<input type="number" />
It has wide support in browsers and it's the standard and best-practice solution.
Also on mobile
and tablets
the numeric key pad will appear instead.
See demo
回答3:
you need some java script to implement this
<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars,"");
}
}
</script>
</head>
<body>
<input type="text" onkeyup="checkInput(this)"/>
</body>
</html>
回答4:
Try this (utilizing jquery javascript library)
html
<input type="text" size="30" />
js (jquery library)
$(document).ready(function() {
$("input").attr("placeholder", "Please input numbers").change(function(e) {
var txt = /[a-z]/gi.test($(this).val());
if (txt) {
$(this).val("").attr("placeholder", "Not a number, please input numbers")
};
});
})
jsfiddle http://jsfiddle.net/guest271314/v2BRY/
Edit. Not certain if element
is input
ot textarea
, hope should work for either.
javascript, without utilizing jquery javascript library
html
<input type="text" size="30" />
javascript
function checkText() {
var textarea = document.querySelectorAll("input");
textarea[0].setAttribute("placeholder", "Please input numbers");
textarea[0].addEventListener("change", function(e) {
var txt = /[a-z]/gi.test(e.target.value);
if (txt) {
e.target.value = "";
e.target.setAttribute("placeholder", "Not a number, please input numbers");
};
}, false);
};
checkText()
jsfiddle http://jsfiddle.net/guest271314/pFu4K/
Hope this helps
回答5:
Yes, you need some JavaScript to do this. I found the JQuery date picker widget very useful to do exactly what you're wanting. The code that used to implement it is:
html to create the text field and not allow manual manipulation:
<input type="text" class="header_input" id="tvpostingdate" placeholder="Posting Date" default='' readonly="readonly">
the JS line binding the picker to the field with a specific format that my server side process is expecting:
$('#tvpostingdate').datepicker({ dateFormat: "mmddyy"});
You can find more information here: http://jqueryui.com/datepicker/