0

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?

2 Answers2

1

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>
Praveen Singh
  • 2,499
  • 3
  • 19
  • 29
  • ha! it was something REALLY stupid. I just didn't have `()` after my .text. But I'm glad I posted, because I still learned some valuable things about keyup/down. Thanks guys! – 5PalmTechnique Jul 12 '15 at 19:12
0

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

Community
  • 1
  • 1
Francisco Goldenstein
  • 13,299
  • 7
  • 58
  • 74
  • That could be the case, but I should still be able to get the unedited text right? The main trouble I'm having is that I'm not sure of the syntax to get at the text. I changed my function to use keyup and I'm getting the same results, but with a return added to the text (which i was trying to avoid). I am using preventdefault. – 5PalmTechnique Jul 12 '15 at 19:05
  • Then syntax to get the value from a p tag is $("p.task-name").text(). I see that you have marked your p tag as contenteditable so check this answer: http://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome – Francisco Goldenstein Jul 12 '15 at 19:08