0

how can I create a button that when clicked, it simulates ENTER as if it were physically pressed on the keyboard.

In other words, this button when clicked simulates the ENTER button inside the text area, where text is being written.

For instance, after the button is clicked,

Original text area text:

XXX XXX XXX

Becomes

New text area text:

XXX XXX XXX

New line

All of this is simulated via a button click.

Let's assume the text area has an ID of #QR

Strictly javascript, no jquery

3
  • 1
    Welcome to SO. Can you please share what you've tried so far? Commented Jan 5, 2017 at 7:30
  • It is likely not a correct duplicate. You perhaps want <button type="button" onclick="document.getElementById("QR").value+='\n';">Enter</button> Commented Jan 5, 2017 at 7:33
  • Unfortunately I didn't know where to begin Commented Jan 5, 2017 at 20:22

2 Answers 2

1

It's pretty easy though. All you have to do is add an event listener on the button like so:

HTML Code:

<textarea id="text_area"></textarea>
<button type="button" id="new_line">Click Me!</button>

JS Code

var textarea = document.getElementById("text_area"),
    myBtn    = document.getElementById("new_line");

myBtn.addEventListener("click", function(){
    textarea.value += "\r\n";
    textarea.focus(); // This is optional, if you want the user to go back into the textarea. This will be good then :)

}, false);

Note that i have declared the variables outside of the function such that on each button click, you don't have to jump into the DOM to look for the textarea over & over again.

Hope that helps :-)

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

Comments

0

html

<textarea id="txtArea"></textarea>
<button type="button" onclick="clickOn()">

js

<script>
function clickOn() 
{
 document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
}
</script>

2 Comments

This is great in the sense that clicking the button adds a new line, but is it possible mimic the actual Keypress of the ENTER button?
yes possible to call for function clickOn() from place you just want

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.