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

http://jsfiddle.net/W5WE8/

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!