Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
¿Cómo saber si el texto en un cuadro de texto está seleccionado?

Tengo cuadros de texto <input type='text'> que solo permiten caracteres numéricos y no permiten que el usuario ingrese un punto (.) más de una vez. El problema es que si se selecciona el texto en el cuadro de texto, el usuario tiene la intención de sobrescribir el contenido con un punto, ¡por lo tanto, lo permite! La pregunta es, ¿cómo puede saber en javascript si el texto en ese cuadro de texto está seleccionado o no?

Gracias

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Lo siguiente le dirá si todo el texto está seleccionado o no dentro de una entrada de texto en todos los navegadores principales.

Ejemplo: http://www.jsfiddle.net/9Q23E/

Código:

 function isTextSelected(input) { if (typeof input.selectionStart == "number") { return input.selectionStart == 0 && input.selectionEnd == input.value.length; } else if (typeof document.selection != "undefined") { input.focus(); return document.selection.createRange().text == input.value; } }
over 4 years ago · Santiago Trujillo Report

0

Respuesta específica de 2017 : se enfrentó al mismo problema recientemente.

Permitíamos a los usuarios ingresar solo 3 dígitos a la vez. Cuando el usuario intentó ingresar el cuarto carácter, devolvimos falso.

Esto se convirtió en un problema cuando el usuario tenía una selección e intentaba sobrescribir los valores.

Tomando una pista de la respuesta de Tim. Entendí que quería ver si el selection value era el mismo que el input's value .

En los navegadores modernos lo logré haciendo:

 document.getSelection().toString() === input.value // edited

Espero que esto ayude a alguien.

over 4 years ago · Santiago Trujillo Report

0

Para cualquiera que necesite el código para acceder al texto seleccionado dentro de un cuadro de texto, aquí hay una versión mejorada:

http://jsfiddle.net/9Q23E/527/

 function getSelection(textbox) { var selectedText = null; var activeElement = document.activeElement; // all browsers (including IE9 and up), except IE before version 9 if(window.getSelection && activeElement && (activeElement.tagName.toLowerCase() == "textarea" || (activeElement.tagName.toLowerCase() == "input" && activeElement.type.toLowerCase() == "text")) && activeElement === textbox) { var startIndex = textbox.selectionStart; var endIndex = textbox.selectionEnd; if(endIndex - startIndex > 0) { var text = textbox.value; selectedText = text.substring(textbox.selectionStart, textbox.selectionEnd); } } else if (document.selection && document.selection.type == "Text" && document.selection.createRange) // All Internet Explorer { var range = document.selection.createRange(); selectedText = range.text; } return selectedText; }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!