June 18, 2013
why i cant empty textarea when i enter
HiDd3N’s Question:
i just setup a jsfiddle in this link and the problem is where i empty textarea one line break stay and i cant see placeholder again and i always one break line is there see this fiddle
my html
<script src="http//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="mytextarea" rows="15" cols="80" placeholder="write something and press enter"></textarea>
and here is my js
$('#mytextarea').keydown(function(e) {
if (e.keyCode == 13) {
$('#mytextarea').val('').focus();
}
});
You need to prevent the default behaviour of the keydown
. As seen here: http://jsfiddle.net/lnrb0b/W5WE8/2/
$('#mytextarea').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
$('#mytextarea').val('').focus();
}
});
Hope that helps 🙂
The main reason why this is happening is because of the enter key. This will add one break line before doing what you need.
Prevent the event propagation as suggested in other answers.