Home > Blockchain >  Unable to detect "Enter key" in Javascript with Php
Unable to detect "Enter key" in Javascript with Php

Time:02-02

I am working with php and javascript, I have texarea and i want whenever i enter any text and press "Enter key" then alert should display,But right now text is going to next line instead of display alert box,

Here is my html code

<textarea  placeholder="Write a comment1…" id="txt'.$FeedId.'" rows="1"  style="overflow:hidden" onkeypress="return Addcomment1(this)"></textarea>

And here is my script code,Where i am wrong ?

<script>
function Addcomment1(e) {
    f (e.keyCode == 13) {
        alert('Hello world');
        return false;
    }
}
</script>

CodePudding user response:

The cause of the problem is that you are passing the textarea element to the function instead of the event object.

Your other issues are that you are using an intrinsic event attribute (which comes with a bunch of gotchas) and the deprecated keyCode property. You also made a typo and misspelt if. Finally, function names starting with a capital letter are traditionally reserved for construction functions, which yours isn't.

const textarea = document.querySelector('textarea');
textarea.addEventListener('keypress', addComment1);

function addComment1(e) {
  if (e.key === "Enter") {
    alert('Hello world');
    e.preventDefault();
  }
}
<textarea placeholder="Write a comment1…" id="txt'.$FeedId.'" rows="1"  style="overflow:hidden"></textarea>


And all that aside, since you have a single line <textarea> where you are blocking the use of the Enter key… you should probably get rid of the JS and just use <input type="text> instead.

CodePudding user response:

The argument this in the function Addcomment1(this) returns the element itself, not the key event that you wish to get so you must use javascript addEventListener to get the event key and use key instead of keyCode as it is a deprecated property

HTML:

<textarea placeholder="Write a comment1…" id="txt'.$FeedId.'" rows="1"  style="overflow:hidden"></textarea>

JS:

let textarea = document.querySelector('.reply_post_new');

textarea.addEventListener('keypress', function(e) {
    if(e.keyCode == 13) {
        alert('Hello world');
        return false;
    }
});
  •  Tags:  
  • Related