Function - Change date format on blank form X

Asked

Viewed 22 times

0

I have a question. I need to fix a date in a form, but if the field is empty, it goes straight through the function and does not execute. If it is previously completed, it makes the change.

Initially I did so, without the validation of the empty field:

  $(document).ready(function AcertaDataInsp() {

  var data = $("#dataInspecao").val();
  var aData = data.split("-");
  var datacompleta = aData[2]+'/'+aData[1]+'/'+aData[0];
  $("#dataInspecao").val(datacompleta);  

  });

My question is, how do I perform the function only if the field is filled? Today if I execute the function above, in the form it fills so "Undefined/Undefined/"

2 answers

0


If I understand, just put one if checking whether the value of data has something and execute the rest of the code. If it is empty, it does not enter the if and does not execute the rest of the code:

$(document).ready(function AcertaDataInsp() {

   var data = $("#dataInspecao").val();

   if(data){
      var aData = data.split("-");
      var datacompleta = aData[2]+'/'+aData[1]+'/'+aData[0];
      $("#dataInspecao").val(datacompleta);  
   }
});
  • It worked this way. The detail of the undefined field is gone. I will test in filled date situations as well.

0

Hello, William. This input you are trying to format is kind date ? If not, I recommend that you use the input date together with the event .on('select', callback). So, you can format the date with the class Date JS itself, the way you want it. Or in a simpler way:

$(document).ready(function AcertaDataInsp() {
    $("dataInspecao").on('select', function(event) {
        var data = $("#dataInspecao").val();
        var aData = data.split("-");
        var datacompleta = aData[2]+'/'+aData[1]+'/'+aData[0];
        $("#dataInspecao").val(datacompleta);  
    });
}); 
  • The format coming from the database is formatted in the international date pattern in String form.

Browser other questions tagged

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