Jahangir Alam
Jahangir Alam

Reputation: 65

textarea keyup event for submit

Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

<script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else
       {
           return;
       }
}
</script>

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.

Upvotes: 1

Views: 863

Answers (3)

Jack jdeoel
Jack jdeoel

Reputation: 4584

It is better to use onkeydown

onkeydown is fired when the key is down

instead of onkeyup

onkeyup is fired when the key is released

You can check shiftkey is pressed by event.shiftKey(true/false)

<script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13 && !event.shiftKey) {
           document.getElementById('commentarea'+postid).value='';
           event.preventDefault();
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
}
</script>

Upvotes: 0

PRADEEP Kumar
PRADEEP Kumar

Reputation: 243

 if (event.keyCode == 13 && event.shiftKey) {
   // shift+enter pressed
 }
 else if(event.keyCode == 13){
          //enter key pressed
}else{
    //nothing
}

Upvotes: 1

Nisarg Shah
Nisarg Shah

Reputation: 14561

You can check if the shift key was pressed or not through event.shiftKey property. So your event handler could be modified to:

function enter_comment(postid,userpostedid) {
       if (event.which == 13 && !event.shiftKey) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else if (event.which == 13 && event.shiftKey)
       {
            // Create the new line.
       }
       else
       {
           return;
       }
}

Upvotes: 0

Related Questions