texto tablas para mas hacer grande formularios formulario ejemplos ejemplo cuadro contraseƱa como cajas boton atributos javascript textbox input

javascript - para - formularios en tablas html



Establecer la posiciĆ³n del cursor del teclado en el cuadro de texto html (7)

¿Alguien sabe cómo mover el cursor del teclado en un cuadro de texto a una posición particular?

Por ejemplo, si un cuadro de texto (por ejemplo, elemento de entrada, no área de texto) tiene 50 caracteres y quiero colocar el símbolo de intercalación antes del carácter 20, ¿cómo lo haré?

Esto se diferencia de esta pregunta: jQuery Establecer la posición del cursor en el área de texto , que requiere jQuery.


Como realmente necesitaba esta solución, y la solución de referencia típica ( enfocar la entrada - luego establecer el valor igual a sí mismo ) no funciona en todos los navegadores , pasé un tiempo ajustando y editando todo para que funcione. Sobre la base del código de @ kd7 , esto es lo que se me ocurrió.

¡Disfrutar! Funciona en IE6 +, Firefox, Chrome, Safari, Opera

Técnica de posicionamiento de intercalación entre exploradores (ejemplo: mover el cursor al FIN)

// ** USEAGE ** (returns a boolean true/false if it worked or not) // Parameters ( Id_of_element, caretPosition_you_want) setCaretPosition(''IDHERE'', 10); // example

La carne y las papas son básicamente setCaretPosition de @ kd7 , siendo el más grande el tweak if (el.selectionStart || el.selectionStart === 0) , en firefox el selectionStart está comenzando en 0 , lo que en booleano por supuesto está cambiando a Falso, entonces estaba rompiendo allí.

En Chrome, el problema más grande era que simplemente darle .focus() no era suficiente (¡seguía seleccionando TODO el texto!) Por lo tanto, establecemos el valor de sí mismo, el el.value = el.value; antes de llamar a nuestra función, y ahora tiene un agarre y posición con la entrada para usar selectionStart .

function setCaretPosition(elemId, caretPos) { var el = document.getElementById(elemId); el.value = el.value; // ^ this is used to not only get "focus", but // to make sure we don''t have it everything -selected- // (it causes an issue in chrome, and having it doesn''t hurt any other browser) if (el !== null) { if (el.createTextRange) { var range = el.createTextRange(); range.move(''character'', caretPos); range.select(); return true; } else { // (el.selectionStart === 0 added for Firefox bug) if (el.selectionStart || el.selectionStart === 0) { el.focus(); el.setSelectionRange(caretPos, caretPos); return true; } else { // fail city, fortunately this never happens (as far as I''ve tested) :) el.focus(); return false; } } } }


El enlace en la respuesta está roto, este debería funcionar (todos los créditos van a blog.vishalon.net ):

http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

En caso de que el código se pierda de nuevo, aquí están las dos funciones principales:

function doGetCaretPosition(ctrl) { var CaretPos = 0; if (ctrl.selectionStart || ctrl.selectionStart == 0) {// Standard. CaretPos = ctrl.selectionStart; } else if (document.selection) {// Legacy IE ctrl.focus (); var Sel = document.selection.createRange (); Sel.moveStart (''character'', -ctrl.value.length); CaretPos = Sel.text.length; } return (CaretPos); } function setCaretPosition(ctrl,pos) { if (ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos,pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd(''character'', pos); range.moveStart(''character'', pos); range.select(); } }


Extraído de Josh Stodola''s Setting keyboard caret Position en un Textbox o TextArea con Javascript

Una función genérica que le permitirá insertar el cursor en cualquier posición de un cuadro de texto o área de texto que desee:

function setCaretPosition(elemId, caretPos) { var elem = document.getElementById(elemId); if(elem != null) { if(elem.createTextRange) { var range = elem.createTextRange(); range.move(''character'', caretPos); range.select(); } else { if(elem.selectionStart) { elem.focus(); elem.setSelectionRange(caretPos, caretPos); } else elem.focus(); } } }

El primer parámetro esperado es la ID del elemento en el que desea insertar el cursor del teclado. Si no se puede encontrar el elemento, no pasará nada (obviamente). El segundo parámetro es el índice de posición de cuidado. Zero pondrá el cursor del teclado al principio. Si pasa un número mayor que el número de caracteres en el valor de los elementos, pondrá el cursor del teclado al final.

Probado en IE6 y versiones posteriores, Firefox 2, Opera 8, Netscape 9, SeaMonkey y Safari. Desafortunadamente en Safari no funciona en combinación con el evento onfocus).

Un ejemplo del uso de la función anterior para forzar el cursor del teclado para saltar al final de todas las áreas de texto en la página cuando reciben el foco:

function addLoadEvent(func) { if(typeof window.onload != ''function'') { window.onload = func; } else { if(func) { var oldLoad = window.onload; window.onload = function() { if(oldLoad) oldLoad(); func(); } } } } // The setCaretPosition function belongs right here! function setTextAreasOnFocus() { /*** * This function will force the keyboard caret to be positioned * at the end of all textareas when they receive focus. */ var textAreas = document.getElementsByTagName(''textarea''); for(var i = 0; i < textAreas.length; i++) { textAreas[i].onfocus = function() { setCaretPosition(this.id, this.value.length); } } textAreas = null; } addLoadEvent(setTextAreasOnFocus);


He ajustado un poco la respuesta de kd7 porque elem.selectionStart evaluará a false cuando el selectionStart es incidentalmente 0.

function setCaretPosition(elem, caretPos) { var range; if (elem.createTextRange) { range = elem.createTextRange(); range.move(''character'', caretPos); range.select(); } else { elem.focus(); if (elem.selectionStart !== undefined) { elem.setSelectionRange(caretPos, caretPos); } } }


Si necesita enfocar algún cuadro de texto y su único problema es que todo el texto se resalta mientras que usted desea que el símbolo de intercalación esté al final, entonces en ese caso específico, puede usar este truco para establecer el valor del cuadro de texto después del foco:

$("#myinputfield").focus().val($("#myinputfield").val());


<!DOCTYPE html> <html> <head> <title>set caret position</title> <script type="application/javascript"> //<![CDATA[ window.onload = function () { setCaret(document.getElementById(''input1''), 13, 13) } function setCaret(el, st, end) { if (el.setSelectionRange) { el.focus(); el.setSelectionRange(st, end); } else { if (el.createTextRange) { range = el.createTextRange(); range.collapse(true); range.moveEnd(''character'', end); range.moveStart(''character'', st); range.select(); } } } //]]> </script> </head> <body> <textarea id="input1" name="input1" rows="10" cols="30">Happy kittens dancing</textarea> <p>&nbsp;</p> </body> </html>


function SetCaretEnd(tID) { tID += ""; if (!tID.startsWith("#")) { tID = "#" + tID; } $(tID).focus(); var t = $(tID).val(); if (t.length == 0) { return; } $(tID).val(""); $(tID).val(t); $(tID).scrollTop($(tID)[0].scrollHeight); }