Object not defined when running in a loop, but not when executed sequentially

javascript, jquery, maskedinput

Solution

The second one is being typed as `number` by `data()`

Since split() is a string method it is throwing error.

Simple fix:

var maskValue = "" + $(this).data('mask');

or

 var maskValue =  $(this).data('mask').toString();

Problem

I'm using the jQuery Masked Input plugin to set all input elements with a data-mask attribute defined to the attribute mask value: Given this html: ``` <input type='text' id="a" data-mask='999?999' /> <input type='text' id="b" data-mask='999' /> ``` And this script: ``` $("input[data-mask]").each(function() { var maskValue = $(this).data('mask'); console.log($(this).attr('id') + ": " + maskValue); //undefined error here on second iteration "b: 999" //no issues if you remove the data-mask from one of the input elements return $(this).mask(maskValue); }); ``` The second iteration an error is thrown: "Uncaught TypeError: undefined is not a function" on this line, saying 'split' is not defined. ``` firstNonMaskPos = null, $.each(mask.split(""), function(i, c) { ``` This code however works just fine, the masks are set with no issue. ``` $('#a').mask('999?999'); $('#b').mask('999'); ``` Could anyone shine any light on this odd behavior? Demo jsFiddle here

Original source