section bootstrap javascript jquery keypress

javascript - bootstrap - ¿Puedo cambiar condicionalmente el carácter ingresado en una entrada al presionar una tecla?



select html (6)

¿No está realmente seguro de lo que quiere pero funcionará?

$(''#my_element'').keyup(function(){ $(this).val().toUpperCase(); });

o usar una cadena secundaria para obtener el último carácter presionado y hacer toUpperCase() en eso?

(psst ... puedes usar keydown o keypress también).

¿Es posible cambiar el carácter que se ha ingresado al presionar una tecla, sin hacerlo manualmente?

Por ejemplo, si quiero forzar letras mayúsculas en función de alguna condición , sería bueno hacer lo siguiente:

function onKeypressHandler(e) { if ( condition ) { e.which -= 32; } }

Pero claro que eso no funciona.

NOTA: Esto no es una mayúscula general, sino solo caracteres específicos.

Tal vez quiero decir if ( e.which >= 97 && e.which <= 102 ) o if ( Wind.Direction == ''South'' ) o lo que sea - la condición en sí no es importante, pero el cambio de mayúsculas solo se aplica a El carácter actual no es la entrada completa.


Puedo hacerlo agregando manualmente el carácter cambiado, pero esta es una manera fea y desordenada de hacerlo, y probablemente más lenta de lo que podría ser.

function onKeypressHandler(e) { if ( condition ) { $j(this).val( $j(this).val() + String.fromCharCode( e.which - 32 ) ); return false; } }

Una falla específica con este método: si selecciona todo el texto de entrada e ingresa una clave, si cae en este, entonces no elimina el contenido existente, sino que simplemente se agrega al contenido que el usuario quería eliminar. (Necesitaría investigar la detección de cualquier texto seleccionado para resolverlo, lo que hace que este sea aún más feo).

¿Alguien puede proporcionar una mejor solución?


¿Puedes usar css?

<input type="text" style="text-transform: uppercase;" />


¿Qué hay de prevenir la acción por defecto y luego activar la pulsación de tecla? Algo como,

function onKeypressHandler(e) { if ( condition ) { e.preventDefault(); // create new event object (you may clone current e) var ne = new jQuery.Event("keypress"); ne.which = e.which - 32; $(e.target).trigger(ne); // you may have to invoke with setTimeout } }


Lo siguiente hará el trabajo. Se basa en una respuesta que escribí a otra pregunta . Personalice la función transformTypedChar para satisfacer sus necesidades; mi ejemplo usa mayúsculas solo las letras ag.

Si necesita esto en un área de texto en lugar de en <input type="text"> , tenga en cuenta que hay problemas en IE <= 8 con saltos de línea que el siguiente código no controla por razones de brevedad. Puede encontrar la función de navegador cruzado para obtener la selección dentro de un área de texto aquí: ¿Existe un sustituto aprobado por Internet Explorer para selectionStart y selectionEnd?

function transformTypedChar(charStr) { return /[a-g]/.test(charStr) ? charStr.toUpperCase() : charStr; } document.getElementById("your_input_id").onkeypress = function(evt) { var val = this.value; evt = evt || window.event; // Ensure we only handle printable keys, excluding enter and space var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode; if (charCode && charCode > 32) { var keyChar = String.fromCharCode(charCode); // Transform typed character var mappedChar = transformTypedChar(keyChar); var start, end; if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") { // Non-IE browsers and IE 9 start = this.selectionStart; end = this.selectionEnd; this.value = val.slice(0, start) + mappedChar + val.slice(end); // Move the caret this.selectionStart = this.selectionEnd = start + 1; } else if (document.selection && document.selection.createRange) { // For IE up to version 8 var selectionRange = document.selection.createRange(); var textInputRange = this.createTextRange(); var precedingRange = this.createTextRange(); var bookmark = selectionRange.getBookmark(); textInputRange.moveToBookmark(bookmark); precedingRange.setEndPoint("EndToStart", textInputRange); start = precedingRange.text.length; end = start + selectionRange.text.length; this.value = val.slice(0, start) + mappedChar + val.slice(end); start++; // Move the caret textInputRange = this.createTextRange(); textInputRange.collapse(true); textInputRange.move("character", start - (this.value.slice(0, start).split("/r/n").length - 1)); textInputRange.select(); } return false; } };



Tienes que ver esto ... Estaba muy feliz conmigo mismo después de que funcionara ...

Obviamente, querría incluir criterios suficientes para evitar entrar en un bucle aquí.

El siguiente código devuelve falso cuando la condición se evalúa como verdadera, pero dispara el mismo evento con un CharCode diferente que no devolverá falso.

document.getElementById("input1").onkeypress = Handler; function Handler(e) { e = e || window.event; if ( e.charCode == 97 ) { var evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent("keypress",true, true, window, false, false,false, false, 0, e.charCode -32); this.dispatchEvent(evt); return false; } return true; }

podría usar fireEvent en IE ... Usé http://help.dottoro.com/ljrinokx.php y https://developer.mozilla.org/en/DOM/event.initKeyEvent para referencia