Cody Coderson
Cody Coderson

Reputation: 421

Can't get JavaScript code to work on Firefox

I've written a code, on which when the form field reaches its max length (in this example 1) the cursor moves to next field.

JS:

window.onload=function(){
var container = document.getElementsByClassName("container")[0];
container.onkeyup = function(e) {
    var target = e.srcElement;
    var maxLength = parseInt(target.attributes["maxlength"].value, 10);
    var myLength = target.value.length;
    if (myLength >= maxLength) {
        var next = target;
        while (next = next.nextElementSibling) {
            if (next == null)
                break;
            if (next.tagName.toLowerCase() == "input") {
                next.focus();
                break;
            }
        }
    }
}
}

HTML:

<div class="container">
<label><input type="text" name="pin1" maxlength="1" pattern="\d{1}" onkeypress="return isNumber(event)" required/>&nbsp;-&nbsp;
<input type="text" name="pin2" maxlength="1" pattern="\d{1}" onkeypress="return isNumber(event)" required/>&nbsp;-&nbsp;
<input type="text" name="pin3" maxlength="1" pattern="\d{1}" onkeypress="return isNumber(event)" required/>&nbsp;-&nbsp;
<input type="text"  name="pin4" maxlength="1" pattern="\d{1}" onkeypress="return isNumber(event)" required/>
</label>
</div>

The form works just fine on Google Chrome and other mobile browsers, but it isn't working on Firefox.

Please help me to get it work on cross browser.

Upvotes: 0

Views: 71

Answers (2)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60587

The problem is you are using the non-standard event property srcElement.

var target = e.srcElement;

From MDN on Event.srcElement:

Event.srcElement is a proprietary alias for the standard Event.target property. It is specific to old versions of Microsoft Internet Explorer.

The only reason it is working in Chrome is this browser currently also aliases this property for compatibility reasons.

Use this instead:

var target = e.target;

Every version if IE requiring srcElement is obsolete, so there is no reason to use this property today.

(I'm assuming you have isNumber defined somewhere, else this will also be a problem.)

Upvotes: 4

Ryan Jenkin
Ryan Jenkin

Reputation: 924

In both Chrome and Firefox, the function isNumber() is not defined.

The other issues is that you're using a non-standard event property srcElement, you should use e.target instead. https://developer.mozilla.org/en/docs/Web/API/Event/srcElement

Upvotes: 1

Related Questions