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

Community
  • 1
  • 1
stylusss
  • 79
  • 2
  • 10

2 Answers2

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 :-)

Zahid Saeed
  • 1,101
  • 1
  • 8
  • 14
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>
L. Vadim
  • 539
  • 3
  • 12
  • 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? – stylusss Jan 05 '17 at 20:22
  • yes possible to call for function clickOn() from place you just want – L. Vadim Jan 09 '17 at 14:44