Tzvi
Tzvi

Reputation: 343

Need to evoke an enter keypress on textarea?

I have this obfuscated webpage that contains a text-area, When a user manually inserts text and presses Enter key while editing the text area an event that changes the DOM launches.

I need to pragmatically launch that event, I know how to get to the text-area itself (using getElementsByName) and I'm basically inserting text via textArea.value = '' How do I get that event to launch?

Upvotes: 0

Views: 192

Answers (2)

Josh Sherick
Josh Sherick

Reputation: 2161

Could you call a function when enter is pressed, and then also just call that function when you want to simulate enter being pressed?

element.addEventListener("keypress", function(event){
    if (event.keyCode == 13) {
        // Enter has just been pressed.
        enterPressed();
    }
});

function enterPressed(){
    // Do whatever you do when enter is pressed.
}

// Somewhere else off in your code when you want to "trigger" the enter press event:
enterPressed();

Upvotes: 1

gaurav5430
gaurav5430

Reputation: 13882

is this what you want

document.getElementById("id_of_your_textarea").addEventListener("keydown", function(e) {
    if (!e) { var e = window.event; }
    e.preventDefault(); // sometimes useful

    // Enter is pressed
    if (e.keyCode == 13) { document.getElementById("id_of_your_textarea").value = '' }
}, false);

EDIT: based on your comment, you can use the trigger

if you can use jQuery.

$('#textArea').trigger('keydown');

Upvotes: 0

Related Questions