Tengo un elemento <textarea>
. ¿Puedo usar JavaScript para detectar que hay (por ejemplo) 10 filas de texto en él?¿Cómo obtener el número de filas en <textarea > usando JavaScript?
Respuesta
Puede acceder al campo a través de Javascript DOM y simplemente contar el número de caracteres de nueva línea.
oArea = document.getElementById('myTextField');
var aNewlines = oArea.value.split("\n");
var iNewlineCount = aNewlines.length();
Esto solo funcionará para
@ Frankie, ¿correcto, pero cómo calcularlo correctamente? – Mask
Puede desactivar el envoltorio si esa es una opción que haría que el número de líneas nuevas = número de filas –
Bueno he encontrado una manera más simple tanto para hacer esto, pero usted tendrá que establecer la línea de altura de la caja de texto en la CSS. Traté de leer la altura de la línea dentro del script ta.style.lineHeight
pero no parece devolver un valor.
CSS
#ta { width: 300px; line-height: 20px; }
HTML
<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea>
Guión
var taLineHeight = 20; // This should match the line-height in the CSS
var taHeight = ta.scrollHeight; // Get the scroll height of the textarea
ta.style.height = taHeight; // This line is optional, I included it so you can more easily count the lines in an expanded textarea
var numberOfLines = Math.floor(taHeight/taLineHeight);
alert("there are " + numberOfLines + " lines in the text area");
Actualización: Gracias a @Pebbl para la elaboración de los insectos, este es el código necesario para conseguir el alto del contenido del texto (demo)
var calculateContentHeight = function(ta, scanAmount) {
var origHeight = ta.style.height,
height = ta.offsetHeight,
scrollHeight = ta.scrollHeight,
overflow = ta.style.overflow;
/// only bother if the ta is bigger than content
if (height >= scrollHeight) {
/// check that our browser supports changing dimension
/// calculations mid-way through a function call...
ta.style.height = (height + scanAmount) + 'px';
/// because the scrollbar can cause calculation problems
ta.style.overflow = 'hidden';
/// by checking that scrollHeight has updated
if (scrollHeight < ta.scrollHeight) {
/// now try and scan the ta's height downwards
/// until scrollHeight becomes larger than height
while (ta.offsetHeight >= ta.scrollHeight) {
ta.style.height = (height -= scanAmount)+'px';
}
/// be more specific to get the exact height
while (ta.offsetHeight < ta.scrollHeight) {
ta.style.height = (height++)+'px';
}
/// reset the ta back to it's original height
ta.style.height = origHeight;
/// put the overflow back
ta.style.overflow = overflow;
return height;
}
} else {
return scrollHeight;
}
}
var calculateHeight = function() {
var ta = document.getElementById("ta"),
style = (window.getComputedStyle) ?
window.getComputedStyle(ta) : ta.currentStyle,
// This will get the line-height only if it is set in the css,
// otherwise it's "normal"
taLineHeight = parseInt(style.lineHeight, 10),
// Get the scroll height of the textarea
taHeight = calculateContentHeight(ta, taLineHeight),
// calculate the number of lines
numberOfLines = Math.ceil(taHeight/taLineHeight);
document.getElementById("lines").innerHTML = "there are " +
numberOfLines + " lines in the text area";
};
calculateHeight();
if (ta.addEventListener) {
ta.addEventListener("mouseup", calculateHeight, false);
ta.addEventListener("keyup", calculateHeight, false);
} else if (ta.attachEvent) { // IE
ta.attachEvent("onmouseup", calculateHeight);
ta.attachEvent("onkeyup", calculateHeight);
}
+1, este es de lejos el enfoque más confiable. Una nota: asegúrese de que el área de texto comience con 'rows = 1', o su' scrollHeight' puede ser artificialmente alto. –
@Mottie el objeto '.style' solo devolverá estilos en línea. Para obtener el valor calculado, debe usar 'window.getComputedStyle' y recurrir a' Elm.currentStyle' para IE antiguo. Aparte de eso +1 :) – Pebbl
Gracias por la entrada @pebbl! Combiné las sugerencias anteriores e hice [una demostración] (http://jsfiddle.net/Mottie/PfD7L/). Tenga en cuenta que cuando cambie manualmente el tamaño del área de texto en los navegadores modernos, la cantidad de líneas cambiará para coincidir con la altura ajustada y no con el contenido. – Mottie
function countLines(area,maxlength) {
// var area = document.getElementById("texta")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g, "")
var split = text.split("\n")
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than "+maxlength.toString()+" lines");
}
return false;
}
esta es una forma sencilla y probada uno
línea Solo una JS:
var rows = document.querySelector('textarea').value.split("\n").length;
He tenido problemas con este, dependiendo del sistema operativo. En particular, la diferencia entre \ r, \ r \ n, \ n \ r, y \ n. No recuerdo exactamente por qué, pero en realidad fue bastante difícil hacerlo exhaustivamente de esta manera. – mike
¿Qué sucede si hay varias líneas no debido a caracteres de nueva línea sino porque una línea se desborda a la línea siguiente? – brandaemon
- 1. Limpiando <textarea> con Javascript?
- 2. Cómo especificar las filas y columnas de una etiqueta usando <textarea > wtforms
- 3. ¿Cómo obtener html <td> valores usando javascript?
- 4. Spring está comiendo</textarea> tags
- 5. Longitud máxima para HTML <textarea>
- 6. Cómo cambiar el contenido de un <textarea> con Javascript
- 7. <textarea> con la regla horizontal
- 8. Javascript y `<> ...</>` etiquetas
- 9. Zend_Db: ¿Cómo obtener el número de filas de una tabla?
- 10. Fuerza <textarea> para ocupar todo el espacio disponible
- 11. Cómo obtener el número de filas con SqlDataReader en C#
- 12. ¿Cómo obtener el número de filas eliminadas en PostgreSQL?
- 13. ¿Cómo obtener el número de filas afectadas en sqlalchemy?
- 14. Obtener el número de filas no ocultas en una tabla
- 15. ¿Dar formato al texto en un <textarea>?
- 16. MySQL obtener el número de filas en una tabla innodb
- 17. Obtenga el número de filas en la tabla usando SQLAlchemy
- 18. Cómo obtener el valor de Codemirror textarea
- 19. ¿Cómo obtener el número de filas de un GridView?
- 20. Cómo se desactivan los elementos <script> usando JavaScript
- 21. número de elementos en Tupla <...>
- 22. Envolviendo javascript en <!-- -->
- 23. Cómo obtener el número de filas insertadas por una transacción
- 24. ¿Cómo obtener el elemento llamante usando Javascript?
- 25. Problema con <input type = 'text' /> y <textarea> width
- 26. ¿Qué significa ">>" y "<<" en Javascript?
- 27. Obtener texto de <option> Etiqueta usando PHP
- 28. Obtener un IEnumerable <T> de un IEnumerable <IEnumerable <T>>
- 29. Usando jQuery, ¿cómo selecciono un rango de filas?
- 30. Obtener el número de filas en una tabla HTML
Es posible que desee para aclarar su pregunta por lo que no se ve como si estuviera tratando de devolver el atributo 'rows =' del elemento 'textarea'. –
¿Por qué querrías hacer esto? Siento una especificación de requisito malo. – Randell