0

I try to use .unmask() function after .blur() (jQuery), but it did not worked.

Please help, this is my code:

$('.cnpj').focus(function()
{
    $(this).mask('99999999/9999-99');
})
.blur(function(e)
{
   if($(this).val().length == 0)
   {
        var mask = '99999999/9999-99';
        $(this).unmask(mask);
        $(this).val('CNPJ');
   }
});

Here is the HTML code:

<input type="text" id="cnpj" name="cnpj" class="cnpj empty entriesFormInput01" value="CNPJ" />

My goal is that when the user don't put any value in the input, the input return with the same value='CNPJ', because I have a lot of input in the form and the label is the value, if the user focus in one input and leave, the input will be empty if no value and i want to, when he leaves the input without a value the first value came back again.

fedosov
  • 1,989
  • 15
  • 26
rafaelphp
  • 43
  • 2
  • 10
  • So which part isn't working - the unmasking or the default value when empty on blur? – chrisfrancis27 Aug 02 '12 at 14:16
  • the unmask(), because if I try without it, the script work fine and the condition of length == 0 return to the input the value 'CNPJ' $(this).val('CNPJ'); so, its the plugin. if you want ai put the code online. thanks – rafaelphp Aug 02 '12 at 19:54

1 Answers1

0

First of all I think that jQuery mask() function doesn't exists as default. There is an plugin for jQuery which can be used like that, is that right? I've found this plugin. I think your code didn't worked because you didn't load this plugin or another one.

$('.cnpj').focus(function(){
    if($(this).val() == 'CNPJ') 
       $(this).val('');
    //$(this).mask('99999999/9999-99');
}).blur(function(){
    if($(this).val().length == 0)
    {
        //var mask = '99999999/9999-99';
        //$(this).unmask(mask);
        $(this).val('CNPJ');
     }
});
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • Matei Mihai I load the plugin with the jquery.js, the function focus() and blur() are working, but i cant pass the value CNPJ came back when the validation length its equal 0, so when the script execute this validation i have to unmask() it, to return the default value thats 'CNPJ', and the problem is in the plugin, because if I try without it, the function $(this).val('CNPJ'); works fine. – rafaelphp Aug 02 '12 at 19:52
  • $('.empty').focus(function(){ var val = $(this).attr('title'); var valAtual = $(this).val(); if(val == valAtual){ $(this).val(''); } else { } }); $('.empty').hover(function(){ var val = $(this).attr('title'); var valAtual = $(this).val(); if(valAtual == ''){ $(this).val(val); } }); – rafaelphp Aug 13 '12 at 14:44