0

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" class="reply_post_new" 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>
0

2 Answers 2

1

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" class="reply_post_new" 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.

Sign up to request clarification or add additional context in comments.

8 Comments

I have two different textboxes in same page so how can i manage both textareas ?
Call addEventListener on each of them.
you mean "document.querySelector('#your id '); " Is this right ?
That's one option. I'd probably give them class names and do it in a loop instead.
How can i get "document.querySelector("#your id"); " value in loop ?
|
0

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" class="reply_post_new" 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;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.