camin10
camin10

Reputation: 13

Textarea does not stop making new line when Enter key is pressed

i don't understand why my textarea won't stop making new lines and won't call function when enter is pressed depsite the fact jquery is to do so. With input it's working ok. And yes i still want that Submit button there.

JavaScript

function da(){

$('#com').unbind('keypress').bind('keypress', function(e){
   var code = e.keyCode ? e.keyCode : e.which;
   if(code == 13) // Enter key is pressed
   {  e.preventDefault();
      chat();
   }
});
}

HTML

<form id='com' method='post'>


Mesaj:<br>
<textarea name='mesaj' rows='7' col='60'></textarea><br/><br/>
<input type='submit' value='Trimite mesaj!' onclick='chat()'>

</form>"

Upvotes: 0

Views: 8776

Answers (3)

Swapnil Motewar
Swapnil Motewar

Reputation: 1088

You can do this check my code and sample example for your reference

$(".Post_Description_Text").keydown(function(e){
		if (e.keyCode == 13)
		{
		e.preventDefault();
      	}
	});
.Post_Description_Text{ 
    width:400px;
    height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<textarea name="comment_text" id="comment_text"  class="Post_Description_Text" rows="5"></textarea>
	<button id="check_btn">click here to check</button>

Upvotes: 0

Abhitalks
Abhitalks

Reputation: 28387

To stop newlines (along with carriage return), you need to capture 10 as well as 13 on keypress using keycode.

See this snippet:

$("textarea").on("keypress", function(e) {
    if ((e.keyCode == 10 || e.keyCode == 13)) {
        e.preventDefault();
        chat();
    }
});

function chat() {
    alert("hello chat");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name='mesaj' rows='7' col='60'></textarea><br/><br/>
<input type='submit' value='Trimite mesaj!' onclick='chat()' />

Upvotes: 6

Magicprog.fr
Magicprog.fr

Reputation: 4100

Try this:

HTML(add id to your textarea):

<form id='com' method='post'>
    Mesaj:<br>
    <textarea name='mesaj' id="mesaj" rows='7' col='60'></textarea><br/><br/>
    <input type='submit' value='Trimite mesaj!' onclick='chat()'/>
</form>

JS(avoid new lines when enter key is pressed):

$('#mesaj').keydown(function(e) {
    if(e.which == 13) {
        e.preventDefault();
        chat();
    }
});

JSFIDDLE: http://jsfiddle.net/ghorg12110/p3ufLjoe/

Upvotes: -1

Related Questions