Reputation: 3361
Okay, first some background, I can't use any javascript library except YUI for this project.
What I'm trying to do is take an input and block it to only allow numeric input. I know this is easier to just do in validation, but the PM wants it onkeypress. What I have was constructed from running around the net and works great in firefox. Unfortunately, this has to be compatible with IE8 and IE6, and it works in neither.
Here is what I have so far:
<script type="text/javascript">
function onlyNumbers(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<input type="text" id="<%=Model.HtmlID %>" value="<%= startingAnswer %>"name="<%=Model.HtmlID %>"
maxlength="<%=maximumLength %>" onkeypress="return onlyNumbers(event);" />
Any ideas on what is wrong with it that is making it not work in IE?
Upvotes: 1
Views: 6376
Reputation: 3361
<script type="text/javascript">
function onlyNumbers(target) {
var newVal = document.getElementById(target).value;
if (isNaN(newVal)) {
document.getElementById(target).value = newVal.replace(/[^0-9.]/g, "");
}
}
</script>
<input type="text" id="<%=Model.HtmlID %>" value="<%= startingAnswer %>"name="<%=Model.HtmlID %>"
maxlength="<%=maximumLength %>" onkeyup="javascript:onlyNumbers('<%=Model.HtmlID %>');" />
It took some extra effort, and a little creativity, but I did get this one figured out. This doesn't really disallow the input, instead it simply wipes out anything that isn't allowed as soon as you let go of the key. Actually works on IE6 too
Upvotes: 2
Reputation: 11519
YUI has text field validation as part of its forms module. An example (YUI 3)
var myForm = new Y.Form({
method : "post",
action : "/test.php?action=submit",
inlineValidation : true,
fields : [
{name : 'input1', type : 'text', label : 'Numbers only: ', validator : 'IntegerField'},
{type : 'submit', label : 'Submit'},
{type : 'reset', label : 'Reset'}
]
});
myForm.render('#formContainer');
Upvotes: 0