jQuery function to format date by .class

1

I'm trying to make a script that gets the class .data from the input and convert the date to pt-br, but I can not do it, I'd like some help.

$.fn.converteData = function(){
    var data  = ($(this).val()).split("-");     
    var dataf = data[2]+data[1]+data[0];    
    $(this).val(dataf); 
    $(this).mask("99/99/9999"); //estou usando o plugin maskedinput
}

$(".data").converteData();


<form>
<label for="dt_nasc">Data de nascimento</label>
<input class="data" name="dt_nasc" type="text" value="1966-11-27">
</form>

I wanted it to already be called automatically for all html inputs with the .data class. I get her in 1966-11-27 this script would be to convert 27/11/1966.

    
asked by anonymous 25.11.2014 / 21:00

1 answer

2

If I understand your question this is to change the formatting of the date:

$('input.data').each(function () {
    var data = new Date(this.value);
    this.value = [data.getDate(), data.getMonth() + 1, data.getFullYear()].join('/');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><labelfor="dt_nasc">Data de nascimento</label>
    <input class="data" name="dt_nasc" type="text" value="1966-11-27" />
</form>

In the code first convert the date to a date object and then give the final format using native methods to fetch the day, year and month.

Another solution, without parse of the date:

$('input.data').each(function () {
    this.value = this.value.split('-').reverse().join('/');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><labelfor="dt_nasc">Data de nascimento</label>
    <input class="data" name="dt_nasc" type="text" value="1966-11-27" />
    <label for="dt_emissao">Data de emissão</label>
    <input class="data" name="dt_nasc" type="text" value="2005-08-25" />
</form>
    
25.11.2014 / 22:02