Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set max-rows to textarea input tag?

Tags:

html

jquery

css

I am building html+css (pure, no BS) chatbox window. I am having serious problems with input for message.

What I am looking for is input where user can write his message. That would be either input on textarea tag. I want efect similar to what FB does when line is full another line starts. That would limit my choices to textarea. I need submit button and also submit on enter. So I use it in form tags.

<form>
<textarea></textarea>
<input type="submit" value="Send message">
</form>

What I do not undestand is how I should format textarea?

  1. How to start from one line and move up to some max-lines value (I want to allow only for lines) and if max-lines is reached then start overflowing message?
  2. How to detect shift+enter to create a new line?
like image 379
Kārlis Janisels Avatar asked Feb 08 '17 10:02

Kārlis Janisels


2 Answers

Try this code

<form>
<textarea rows="10" cols="10" maxlength="200" style="resize:none;"></textarea>
<input type="submit" value="Send message">
</form>

$(document).ready(function() {
    $('textarea').live("keypress", function(e) {
        if (e.keyCode == 13) 
        {
            $('form').submit();
        }
    });
});
like image 88
Ganesh Radhakrishnan Avatar answered Oct 13 '22 15:10

Ganesh Radhakrishnan


This might help (probably be best using jQuery, onDomReady and unobtrusively adding the keydown event to the textarea) :

<html>
  <head><title>Test</title></head>
  <body>
    <script type="text/javascript">
      var keynum, lines = 1;

      function limitLines(obj, e) {
        // IE
        if(window.event) {
          keynum = e.keyCode;
        // Netscape/Firefox/Opera
        } else if(e.which) {
          keynum = e.which;
        }

        if(keynum == 13) {
          if(lines == obj.rows) {
            return false;
          }else{
            lines++;
          }
        }
      }
      </script>
    <textarea rows="4" onkeydown="return limitLines(this, event)"></textarea>
  </body>
</html>

*Edit - explanation: It catches the keypress if the ENTER key is pressed and just doesn't add a new line if the lines in the textarea are the same number as the rows of the textarea. Else it increments the number of lines.Use it as your need.

like image 2
Rana Ghosh Avatar answered Oct 13 '22 15:10

Rana Ghosh