简体   繁体   中英

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.

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM