Clear Field with Javascript

Asked

Viewed 4,572 times

3

I am using this function below, to validate the date in all fields of the form date type, call the function in txt onBlur event.

 function VerificaData(digData) {
            var bissexto = 0;
            var data = digData;
            var tam = data.length;
            if (tam == 10)
            {
                var dia = data.substr(0, 2);
                var mes = data.substr(3, 2);
                var ano = data.substr(6, 4);
                if ((ano > 1900) || (ano < 2100)) {
                    switch (mes)
                    {
                        case '01':
                        case '03':
                        case '05':
                        case '07':
                        case '08':
                        case '10':
                        case '12':
                            if (dia <= 31)
                            { return true; }
                            break;
                        case '04':
                        case '06':
                        case '09':
                        case '11':
                            if (dia <= 30)
                            { return true; }
                            break;
                        case '02':
                            if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                            { bissexto = 1; }
                            if ((bissexto == 1) && (dia <= 29))
                            { return true; }
                            if ((bissexto != 1) && (dia <= 28))
                            { return true; }
                            break;
                    }
                }
            }
            alert("A Data " + data + " é inválida!");
            
            return false;
        }

But I would like to know how do I so that when the date is invalid, clear the field ? I tried to form that it would work, if it was a txt and a function, but I use this function for several txts, so the ways I tried, and I researched didn’t work. That’s what I call the job:

onBlur="VerificaData(this.value);

  • 1

    Hello Mariana! This date check function seems to me unnecessarily complex. You can give examples of dates she receives and what she intends to detect wrong?

3 answers

4


You can build another function that interprets the result of the date check and clears if you don’t receive true:

function limparDataInvalida(campo){
     if (!VerificaData(campo.value)){
          campo.value = '';
     }
}

And the onblur is now without the .value, thus:

<input ... onblur="limparDataInvalida(this);">

Edit

To avoid the endless cycle of loops due to the fact that the alert inside VerificaData call the onblur can:

  • Show the message otherwise than with a alert, for example with a message from Jquery UI Dialog

Or

  • Do not validate the date if it has already been cleared and so is empty by modifying the if to look like this:

    function limparDataInvalida(campo){
        //agora aqui vê primeiro se não é vazio
        if (campo.value != '' && !VerificaData(campo.value)){
            campo.value = '';
            campo.focus();
        }
    }
    
  • Gave just Isac, thank you very much. How do I get the Focus set to the date field ? Because it jumps to the bottom txt. Thank you.

  • To keep Focus in the field that has invalid date can do campo.focus(); after the campo.value = ''; that’s inside the if. But be careful that this causes the user not to be able to write in any more boxes of the page until right on that date.

  • I did it this way, only the warning message, goes in infinite loop.

  • 1

    @marianac_costa The problem is that the alert that’s inside VerificaData force a call to onblur, and give the infinite cycle. I already put a solution to this.

  • thank you very much, it worked super well, and it worked the way I needed it.

3

Even though the answer was given by @Isac, I wanted to leave here my contribution.

You can use a completely Javascript solution without having to pass anything to HTML. Particularly because I like to keep everything separate (HTML, CSS, JS, PHP, Python, Java, etc).

You can add a Event Listener to the document to monitor the Blur of the date type Forms or the class containing the date values, then perform its function.

Getting to know the Document Object Model is an excellent way to not get lost. Study it! You will not regret.

EDITION

Using Javascript only

First method, without prototype:

// Seleciona os input tipo datanuma NodeList
var inputTipoData = document.querySelectorAll('input[type="date"]'),
    // Seleciona os input com a classe .date numa NOdeList
    inputClasseData = document.getElementsByClassName('date');

// Aplica o addEventListener para os input com tipo date
for (var i = 0; i < inputTipoData.length; i++) {
    inputTipoData[i].addEventListener('click', alertaOnBlur);
}

// Aplica o addEventListener para os input com classe date
for (var i = 0; i < inputClasseData.length; i++) {
    inputClasseData[i].addEventListener('blur', alertaOnBlur);
}
// Declara a função que será executada
function alertaOnBlur () {
    alert("Blur!!!");
};

Second method, with prototype:

// Cria um protótipo para iterar uma NodeList monitorando cada elemento com 
// addEventListener
NodeList.prototype.addEventListener = function(event, func) {
    this.forEach(function(content, item) {
       content.addEventListener(event, func);
    });
}

// Função definida por mim
function minhaFuncao () {
    alert("AAAHHHHHHH!!!");
}

// Pega todos os formulário tipo date na página
var formularioDate = document.querySelectorAll("input[type='date']");

// Monitora todos os formulários da lista acima com addEventListener
formularioDate.addEventListener("blur", minhaFuncao);
  • 1

    querySelectorAll('input[type="date"]').addEventListener will give error, the addEventListener does not work on collections like the querySelectorAll gives.

  • Perfect, @Sergio. Thank you so much for the correction. I saw that you already edited the reply. Thanks again.

  • Tony: I didn’t edit the answer. The error is still there (in your answer). And you have the same problem in getElementsByClassName("classe-data").addEventListener...

  • And where did that one come from All then? I know that querySelectorAll can work within a loop, used together with addeventlistener. The answer should be querySelector only. My stupid mistake.

  • 1

    And you have the same problem in getElementsByClassName which also returns a collection.

  • Fuck! I didn’t know that. I’m going to make a tested solution to this question. Thank you!

Show 1 more comment

2

You can also, instead of creating a new function, in the same function VerificaData(digData) add the code below after the alert:

window.focus();
campos = document.getElementsByTagName("input");
for (var x=0; x < campos.length; x++) {
  if(campos[x].value == digData) {
    campos[x].value = "";
  }

}

This code will check the field with value sent in digData and empty it.

The window.focus(); is to take the focus() of the field to prevent the alert become infinite.

Your code would look like this:

function VerificaData(digData) {
            var bissexto = 0;
            var data = digData;
            var tam = data.length;
            if (tam == 10)
            {
                var dia = data.substr(0, 2);
                var mes = data.substr(3, 2);
                var ano = data.substr(6, 4);
                if ((ano > 1900) || (ano < 2100)) {
                    switch (mes)
                    {
                        case '01':
                        case '03':
                        case '05':
                        case '07':
                        case '08':
                        case '10':
                        case '12':
                            if (dia <= 31)
                            { return true; }
                            break;
                        case '04':
                        case '06':
                        case '09':
                        case '11':
                            if (dia <= 30)
                            { return true; }
                            break;
                        case '02':
                            if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                            { bissexto = 1; }
                            if ((bissexto == 1) && (dia <= 29))
                            { return true; }
                            if ((bissexto != 1) && (dia <= 28))
                            { return true; }
                            break;
                    }
                }
            }

            alert("A Data " + data + " é inválida!");
            window.focus();

            campos = document.getElementsByTagName("input");
            for (var x=0; x < campos.length; x++) {
                if(campos[x].value == digData) {
                    campos[x].value = "";
                }
            }            
            return false;
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.