LandonRaymond LandonRaymond - 3 years ago 215
jQuery Question

Change dynamically number of rows on submit

I need your help guys.
I use a textarea that automatically expands by changing the number of rows.
In my project, the page does not reload and stays as it is after submitting the form. I need to change dynamically the number of rows (2) on submit.
Also one can send the form by Enter. So I need to change the number of rows after pushing a button or hitting the Enter key.
I've coded a rough sketch of the form that I have in my project so that you could test it:

<form id="NewMessage">
<textarea id="shoutbox-comment" data-min-rows="2"></textarea>
<button id="send_message" type="submit" onclick="chatSubmit();">send</button>


// auto-resizing textarea
const textarea = document.getElementById("shoutbox-comment");

textarea.addEventListener("input", function() {
this.rows = 2; // Erm...
this.rows = countRows(this.scrollHeight);

function countRows(scrollHeight) {
return Math.floor(scrollHeight / 20); // 20px = line-height: 1.25rem

// submit by Enter
$(document).ready(function() {
$("#shoutbox-comment").on("keypress", function(event) {
if (event.keyCode == 10 || event.keyCode == 13) {

// submit FORM
function chatSubmit() {

Thank you!

Answer Source

jQuery submit accept as parameter a callback that is triggered before submit so, you can do:

$("#NewMessage").submit(function( event ) {
  $('#shoutbox-comment').attr('rows', 2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download