racumin
racumin

Reputation: 402

Javascript working in Chrome but not in IE

I'm new to javascript. I have an input box that only accepts numbers. If someone copy-paste on that input, it should trim all the non numeric characters. The input field should only be max 10 characters.

Here is the code. It is working in Chrome but not in IE. Can someone figure out what is wrong?

<!DOCTYPE html>
<html>
<body>

<input type="text" maxlength="10" title="Number" pattern="[0-9]*" onkeypress='validate(event)' onpaste="strip(this, event)"/>

<p id="demo"></p>

<script>
        function strip(obj, evt) {
            var theEvent = evt || window.event;
            obj.value = theEvent.clipboardData.getData('Text').replace(/\D/g, '');
obj.value = obj.value.substring(0,Math.min(10,obj.value.length));
            theEvent.returnValue = false;
        }

        function validate(evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
        }
</script>

</body>
</html>

Chrome Version - Version 40.0.2214.115 m IE Version - 9.0.8

Upvotes: 0

Views: 106

Answers (3)

Tom
Tom

Reputation: 4180

replacing your strip function with the following works:

function strip(input, evt) {
    var clipboardData = window.clipboardData ? window.clipboardData : evt.clipboardData;
    var theEvent = evt || window.event;
    var text = clipboardData.getData('Text');
    var processedText = text.replace(/\D/g, '').substring(0, Math.min(10, text.length));
    input.value = processedText;
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
}

Upvotes: 1

Ferdi
Ferdi

Reputation: 33

You could use a input with type number instead to prevent insertion of characters other than numbers. However this input type is relatively new and will not work on some older browsers.

Small example:

<form>This will allow anything.
<input type="text">
<br />This will allow only numbers.
<input type="number">
<br />Try typing in letters in the bottom box and pressing send.
<br />
<input type="submit">

http://jsfiddle.net/yqdsaf3t/

http://caniuse.com/#feat=input-number

Upvotes: 0

Nejc Rodošek
Nejc Rodošek

Reputation: 163

You are using attribute pattern which is new attribute in HTML5 and is not supported by IE below version 10.

Upvotes: 0

Related Questions