An object is not defined when it starts in a loop, but not when executed sequentially

I use jQuery Masked Input plugin to set all input elements with the data mask attribute defined for 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 is thrown: "Uncaught TypeError: undefined is not a function" on this line, because "split" is not defined.

 firstNonMaskPos = null, $.each(mask.split(""), function(i, c) { 

This code, however, works very well; masks are installed without problems.

 $('#a').mask('999?999'); $('#b').mask('999'); 

Can anyone shed light on this strange behavior?

JsFiddle demo here

+5
source share
2 answers

The second is typed as number on data()

Since split () is a string method, it throws an error.

Simple fix:

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

or

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

Change .data('mask') to .attr('data-mask') . Now it works fine for me for some reason ... Maybe the jQuery version is bundled?

+1
source

Source: https://habr.com/ru/post/1214255/


All Articles