How to add a feature to jQuery?

Asked

Viewed 45 times

2

I have some ready-made functions that format date, take only string numbers, block fields so as not to 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 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.

  • 1

    http://stackoverflow.com/questions/9550866/how-to-create-custom-jquery-function-and-how-to-use-it

  • Settle this with jQuery fn extend

1 answer

4


Considering that it had been commented by the friends above the jQuery.fn.extend restricts extensions to jQuery nodes by summarizing the extensions only applicable to jQuery type elements so you could not use the respective ones after using the method $('seletor').val() 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>
<input type="text" class="cpf" value="123.123.123.01" />
<input type="text" class="data" value="16/03/1990" />

Browser other questions tagged

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