tery.blargh tery.blargh - 2 months ago 22
Javascript Question

How to programmatically click on a text input using JQuery?

I'm trying to implement a messaging application in my game, so instead of clicking on the input text field manually, I want users to only press "enter", write something, then press "enter" again to submit.

For some reason, when I do this (press "enter"), the

onclick
alert fires from the input, but the input stays the same, I am still not able to type into the input form. If I manually click it, it works fine.

Am I missing something?

HTML

<form id="messageInput" action="">
<input id="m" autocomplete="off" maxlength="100" onclick="alert('clicked')"/>
</form>


JAVASCRIPT

if(keyOn["enter"]){
keyOn["enter"] = false;

$('#m').click();

console.log("clicked");
}

Answer Source

Thank you all for your help, but I somehow found the solution by randomly checking everything I saw:

$("#m").trigger("focus");

Use focus instead of click