How to add a functionality to jQuery? [duplicate]

2

I have some ready-made functions that format date, take only strings numbers, block fields to not allow letters etc. Examples:

function formatarData(data){
    // conteúdo da função
    return data;
}

function somenteNumeros(campo){
    // conteúdo da função
}

How do I add this to jQuery so that it works like this:

var dataFormatada = $("#data").val().formatarData();
$("#cpf").somenteNumeros();

My intention is to have a custom jQuery for me to reuse in my applications.

    
asked by anonymous 07.01.2016 / 13:44

1 answer

4

Given what was commented out by friends above jQuery.fn.extend restricts extensions to jQuery nodes in short, extensions will only apply to elements of type jQuery so you could not use theirs after using the $('seletor').val() method which returns a string, the correct invocation would be $('seletor').funcao() where the function would return the string.

Example:

$.fn.formatarData = function() {
  // conteúdo da função
  return this.val();
};

$.fn.somenteNumeros = function() {
  // conteúdo da função
  return this.val();
  
};



alert($('.data').formatarData());
alert($('.cpf').somenteNumeros());

// conforme alertado acima a instrução abaixo retornaria uma exception porque a função
// formatarData está atrelada somente a nodes da jQuery e o resultado o .val() constitui
// uma string.
// alert($('.data').val().formatarData())
// função implementada:

String.prototype.formatarData = function() {
  // conteúdo da função
  return ('string funcao 2 usando val: ' + this);
};

alert($('.data').val().formatarData())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" class="cpf" value="123.123.123.01" />
<input type="text" class="data" value="16/03/1990" />
    
07.01.2016 / 14:46