Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 817
asawyer Avatar asked Feb 26 '15 16:02

asawyer


2 Answers

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();
like image 69
charlietfl Avatar answered Nov 07 '22 21:11

charlietfl


Change .data('mask') with .attr('data-mask'). Works fine now for me for some reason... Maybe jQuery version related?

like image 44
Jeremy Thille Avatar answered Nov 07 '22 22:11

Jeremy Thille