Cody Codes Cody Codes - 1 month ago 14
HTML Question

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.

Answer

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