igorescobar / jQuery-Mask-Plugin

A jQuery Plugin to make masks on form fields and HTML elements.
http://igorescobar.github.io/jQuery-Mask-Plugin/
Other
4.77k stars 1.42k forks source link

Mask not applied to dynamically loaded input field #72

Closed jolyon2000 closed 10 years ago

jolyon2000 commented 10 years ago

I have a page which loads the jquery mask plugin. Then, when clicking a button, the page dynamically loads a new input=text field. However, this new input field does not have the mask applied to it - I have tried with both the $.mask and data-mask attribute.

igorescobar commented 10 years ago

Yeah @jolyon2000 You're right, that is because our plugin doesn't use live/delegate or on() method with the third argument under the hood. At this point you have to figure it out how to call your masks functions again when a new input field is attached to your screen. Or you can wait a few days/weeks until this be implemented. ;-)

mikerogne commented 10 years ago

Looks like this was never implemented.

igorescobar commented 10 years ago

@mikerogne you're wrong. The feature was originally implemented using live events. But it was removed from the source after a few months. Now I need to implement this using .on.

There is a "workaround": http://jsfiddle.net/56pud/ Just to make your development flow until it's not 100% done.

mikerogne commented 10 years ago

Thanks! I ended up just using my own .on() just a few seconds ago.. cleaner anyway in this particular use-case for me. Good work!

igorescobar commented 10 years ago

@mikerogne you're right! It's more easy to implement it on your own code instead of implement it on a generic manner.

mikerogne commented 10 years ago

One issue I ran into... client wants to format/mask money, but wants to assume whole numbers. Any idea how I'd go about that? Instead of doing the decimal first. Here's current mask:

$('.money').mask('000,000,000,000,000.00', {reverse: true});

If you want to tell me to bugger off b/c of wrong area, I understand.

mikerogne commented 10 years ago

Example: If I enter "1500", it assumes $15.00, instead of 1,500

igorescobar commented 10 years ago
 $('.money2').mask("#.##0,00", {reverse: true, maxlength: false});

Doesn't fit your needs?

mikerogne commented 10 years ago

Not quite... I thought it did at first.

I changed it to: $('.money').mask("#.##0,000", {reverse: true, maxlength: false});

If I enter in: 1500, it puts: 1,500 - which is perfect. But I need to be able to specify a decimal and 2 figures after.

Putting: 12345678 gets me: 12.345,678 - which isn't the desired effect :(

igorescobar commented 10 years ago

@mikerogne on that case I think you should go to a plugin specific for currency problems.

mikerogne commented 10 years ago

Yeah, probably right. I'm seeing if client is OK with strictly whole numbers, because then it works perfectly. Thanks a bunch!

igorescobar commented 10 years ago

@mikerogne anytime!

lfbittencourt commented 9 years ago

Já há um jeito "oficial" de fazer isso agora, @igorescobar?

igorescobar commented 9 years ago

Sim veja a doc ;)

[]'s Igor

On 27/10/2014, at 18:19, LF Bittencourt notifications@github.com wrote:

Já há um jeito "oficial" de fazer isso agora, @igorescobar?

— Reply to this email directly or view it on GitHub.

lfbittencourt commented 9 years ago

@igorescobar OK, mea culpa por não ter lido toda a documentação. De qualquer forma, até agora não rolou: http://jsfiddle.net/090gx31n/. Alguma luz?

Muito obrigado.

igorescobar commented 9 years ago

@lfbittencourt seu fiddle abriu com todos os containers em branco...

igorescobar commented 9 years ago

Eu tenho um fiddle que exemplifica como funciona: http://jsfiddle.net/igorescobar/x2mhx0Ld/

Espero que ajude.

lfbittencourt commented 9 years ago

Eita, só bola fora, hehe. Enfim, já tinha visto seu fiddle, mas... Os inputs adicionados dinamicamente não deveriam carregar com máscara? Pelo menos aqui, eu consigo digitar qualquer coisa dentro dos novos campos.

E ah, desculpa pelo flood.

igorescobar commented 9 years ago

@lfbittencourt FUCK! there was a bug. Clear your cache and test my fiddle again ;)

lfbittencourt commented 9 years ago

@igorescobar Rá!

Mas qual a chance desse bugfix ter introduzido outro bug? Quando eu usava uma versão anterior (1.7.8), apenas setar o atributo data-mask nos campos era suficiente para aplicar a máscara, sem nenhuma linha de JS. Esse é o comportamento esperado agora?

P.S.: isso acontece independentemente do objeto $.jMaskGlobals.

igorescobar commented 9 years ago

Você está correto, nas DOCs tem a explicação das flags.

O watchDataMask vem como falar por default por questões de performance. Se quiser usar, habilite.

[]'s Igor

On 28/10/2014, at 14:35, LF Bittencourt notifications@github.com wrote:

@igorescobar Rá!

Mas qual a chance desse bugfix ter introduzido outro bug? Quando eu usava uma versão anterior (1.7.8), apenas setar o atributo data-mask nos campos era suficiente para aplicar a máscara, sem nenhuma linha de JS. Esse é o comportamento esperado agora?

P.S.: isso acontece independentemente do objeto $.jMaskGlobals.

— Reply to this email directly or view it on GitHub.

lfbittencourt commented 9 years ago

@igorescobar Há uma situação específica em que há, sim, um bug. Tente acompanhar comigo:

  1. Como eu disse em um comentário anterior, eu uso teu plugin setando apenas atributos data-mask* nos campos necessários. Note que eu não faço escrevo nenhuma instrução JS! Ou seja, não há $(...).mask(...) em lugar nenhum!
  2. Quando eu clono um desses campos data-mask*, a máscara não é aplicada no clone.

Isso acontece porque a propriedade watchInputs só é levada em consideração quando há uma chamada explícita $(...).mask(...), o que não é o caso. Uma solução poderia ser colocar um intervalo neste trecho:

if (globals.dataMask) {            
    $(globals.dataMaskAttr).each(HTMLAttributes);
}

Aliás, é por isso que funciona com elementos não-input, porque para eles sim há um intervalo:

if (globals.watchDataMask) {
    setInterval(function(){
        $(document).find(globals.nonInput).filter(maskAttr).each(HTMLAttributes);
    }, interval);
}

Acho que fui mais claro agora, mas posso criar um fiddle, se tu ficar com dúvidas.

igorescobar commented 9 years ago

@lfbittencourt de uma olhada no meu jsfiddle: http://jsfiddle.net/igorescobar/x2mhx0Ld/

Acho que agora está tudo ok.

lfbittencourt commented 9 years ago

@igorescobar Em parte. Quando tu clona um elemento que já tinha máscara, ele já contém um data('mask') e por isso não passa na função notSameMaskObject, a menos que tu remova o data explicitamente usando $(...).removeData('mask');.

Ou seja, não sei se é um atributo muito confiável para determinar se é ou não o mesmo objeto de máscara, mas daí já dá margem a interpretações :-)

igorescobar commented 9 years ago

@lfbittencourt se você está clonando o elemento por sua conta em risco, não tem muito que eu possa fazer neste caso, certo?

lfbittencourt commented 9 years ago

@igorescobar Essa é uma interpretação completamente razoável :-) De qualquer forma, obrigado por fazer os ajustes necessários.

igorescobar commented 9 years ago

Se você tiver uma ideia melhor, estou aberto a sugestões ;)

[]'s Igor

On 06/11/2014, at 16:13, LF Bittencourt notifications@github.com wrote:

@igorescobar Essa é uma interpretação completamente razoável :-) De qualquer forma, obrigado por fazer os ajustes necessários.

— Reply to this email directly or view it on GitHub.

bordallorafael commented 7 years ago

Mesmo fazendo um tempo o tópico.. minha solução para mascaras em inputs dinâmicos foi:

$('body').on('focus', 'input[data-mask="hour"]', function(){ $(this).mask("00:00"); });

Espero ajudar!

shayckspear commented 4 years ago

Revivendo o tópico, estou com o mesmo problema, mas no meu caso eu uso JS com .mask.

Até consegui uma solução razoável para aplicar a máscara a campos clonados, basta nesse caso remover a mascara antes de clonar o campo e adicioná-la novamente, o problema está em um caso específico (pelo menos até agora), no caso de moeda onde eu uso a mascara:

$('.real').mask('#.##0,00', {reverse: true});

a máscara é aplicada, mas não fica REVERSE true, alguma solução ?