5PalmTechnique
5PalmTechnique

Reputation: 29

Get text on keydown from contenteditable <p> w/ jquery

I've got a <p class="task-name" contenteditable> and i want to get the text from it when the user presses enter after doing some editing. I've got the event handled...

$(document).on('keypress', 'p.task-name', function(event) {
    if(event.which == 13) {
}

...but for some reason I can't figure out how to get the value of the entered text. I've tried using $(this).text and event.target, but i'm getting a lot of undefineds. I haven't had trouble with other events this way, so I must be missing something fundamental. What am I missing?

Upvotes: 0

Views: 1170

Answers (2)

Francisco Goldenstein
Francisco Goldenstein

Reputation: 13767

You are using keydown which means the key is down, of course, and the tag has not yet been updated. Why? because you could reject that character if you want (you could avoid the user from typing letter in order to have a numeric field, for example). So, you need to handle keyup event instead because at that point, the field is already set and you'll be able to get the valud using text property.

If you wanted to reject a character typed by the user, you should use keydown event. And then you grab the value on keyup event.

In order to avoid the DIV created by contenteditable, see this answer: Prevent contenteditable adding <div> on ENTER - Chrome

Upvotes: 0

Praveen Singh
Praveen Singh

Reputation: 2569

Try this snippet.

$(document).ready( function() {
    $('.x').on('keyup', function(event) {
        if (event.keyCode === 13) {
            console.log($(this).text());
        }
    });
});
.x {
    height:100px;
    width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p class="x" contenteditable>Dummy text</p>

Upvotes: 1

Related Questions