Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
Onclick anywhere on word get position number of word inside textarea - JQuery

this is my code. It works only when I click on the first letter of any word. Then it gives me the position of that word like 0 for first word, 1 for second and etc. But when when I click on middle or anywhere then It don't take position number until I don't click on the start of first letter. Here's how my code is running:

$("#checktext").on('click', function(e) {
         var text = document.getElementById("checktext").value,
        element = $("#checktext")[0],
        arr1 = text.split(" "),
        length = 0,
        selectIndex = element.selectionStart;
         if (selectIndex == 0) {
        console.log(arr1.indexOf(arr1[0]));
         } else {
        for (var i = 0; i < arr1.length; i++) {
             length = length + arr1[i].length + 1;
             if (length == selectIndex) {
            console.log(i + 1);
            break;
             }
        }
        }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script>
<textarea id="checktext">This will only work if click on start of each letter.</textarea>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The Problem is in your condition:

length == selectIndex

This is only true for the first letter of every word. But you want it to be true for the range of letters for every word:

selectIndex >= startOfWord && selectIndex <= endIndexOfWord

$("#checktext").on('click', function(e) {
  var text = document.getElementById("checktext").value,
    element = $("#checktext")[0],
    arr1 = text.split(" "),
    length = 0,
    selectIndex = element.selectionStart;
  for (var i = 0; i < arr1.length; i++) {
    let start = length; // start index of the next word to check
    length = length + arr1[i].length; // end index of your next word to check
    if (selectIndex >= start && selectIndex <= length) {
      console.log("Selected Index: " + i);
      break;
    }
    length++; // add the whitespace after the check
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="checktext">This will only work if click on start of each letter.</textarea>

Also: you probably should use a different variable name instead of length. It is not the length but the end index of your word. I guess thats a part why this error occured, you expect that variable to be something different than it is.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda