Skip to content

Instantly share code, notes, and snippets.

@handersonbf
Created July 18, 2011 18:25
Show Gist options
  • Select an option

  • Save handersonbf/1090241 to your computer and use it in GitHub Desktop.

Select an option

Save handersonbf/1090241 to your computer and use it in GitHub Desktop.
JavaScript para avançar e voltar em campos inputs
/**
* Verifica se a a tecla que foi digitada foi o tab ou o enter, e assim dispara
* o evento de blur no elemento que chamou.<br>
* Recebe um novo parametro para ao digitar HOME ou Seta para cima voltar para o campo desejado.
*
* @author Handerson Frota [ [email protected] ]
*
* @param {Object}
* e evento
* @param {Object}
* idPrev campo que chamou a função ( jQuery(#ID_DO_CAMPO) )
* @param {Object}
* idNext campo que terá o foco ( id_do_campo )
* @param {Object}
* idBack campo que se deseja voltar (id_do_campo)
*/
var setarFoco = function(e, idPrev, idNext, idBack){
var tecla;
var idCampo = "#" + idNext;
var idCampoBack = "#" + idBack;
if (jQuery.browser.msie) {//IE e captura a tecla
tecla = e.keyCode;
}
else
if (e.which) { // Netscape - captura a tecla
tecla = e.which;
}
// se a tecla foi enter ou o tab
if (tecla == 13) {
idPrev.blur();
jQuery(idCampo).focus();
}
// se a tecla for HOME ou seta para cima(38) voltar ao campo anterior
if ((tecla == 36 || tecla== 38) && idCampoBack != "#") {
jQuery(idCampoBack).focus();
}
};
Uso:
jQuery.noConflict();
jQuery("#input01").keydown(function(e){
setarFoco(e, jQuery(this), "input02", "");
});
jQuery("#input02").keydown(function(e){
setarFoco(e, jQuery(this), "input03", "input01");
});
jQuery("#input03").keydown(function(e){
setarFoco(e, jQuery(this), "", "input02");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment