0

i was just wondering if there is anyway to auto press the enter key in an input field after setInterval auto fills from with string?

setInterval(function () {
  document.getElementById('hudinput').value = Math.random().toString(36).substring(2, 15);
}, 5000);
<div id="hudid" class="hudclass">
  <input type="text" name="hud" id="hudinput" class="hud-input" placeholder="Enter text here..." maxlength="140">
</div>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 3
    Is it in a `form` or something? Select the form and submit it, or call whatever handler that's triggered when `enter` is pressed – CertainPerformance Aug 14 '18 at 02:33
  • 1
    Yeah, I have to ask _"why"_? This immediately sounds like an [XY Problem](http://xyproblem.info) – Phil Aug 14 '18 at 02:35
  • Possible duplicate of [Is it possible to simulate key press events programmatically?](https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically) – Phil Aug 14 '18 at 02:38
  • whats the problem its not working? in post you coded is works fine every 5 sec it changing its value – Munkhdelger Tumenbayar Aug 14 '18 at 02:40

1 Answers1

1

Pressing enter in the textbox makes no sense to me, so I'm trying to guess what you want.

Sending a form

If you have something like this:

<form method="post" id="theForm">
    <div id="hudid" class="hudclass">
        <input type="text" name="hud" id="hudinput" class="hud-input" placeholder="Enter text here..." maxlength="140">
    </div>
</form>

and you want to send this form, just call document.getElementById("theForm").submit() in your setInterval function.

Since you're using setInterval, you may also want to see ajax. jQuery.ajax is a good first choice.

Appending a new line

Are you trying to appending a new line in a textbox? No, <input type="text"> is not a multiline textbox. You would like to use a <textarea>.

And if you want to append a new line, you can just append a new line and focus instead of pressing enter in it.

setInterval(function () {
  document.getElementById('hudinput').value = Math.random().toString(36).substring(2, 15);
  document.getElementById('hudinput').value += "\n";
  document.getElementById('hudinput').focus();
}, 5000);
<textarea id="hudinput" class="hud-input" placeholder="Enter text here..." maxlength="140" cols="40" rows="5"></textarea>
NoobTW
  • 2,466
  • 2
  • 24
  • 42