0

Hi i'm new to JS and could use some help.

So I am basically trying to send some text from a textarea to a function called inputFromText on a submit button click event, but somehow the function is being triggered before the click (when opening the html window via electron) and nothing happens when you click the button afterwards.

How do I prevent this from happening?

<body>
  <form>
    <div class="form-group">
      <textarea class="form-control" rows="5" id="txa_trainingText"></textarea>
      <button type="submit" class="btn btn-default" id="btn_submit">Submit</button>
    </div>
  </form>
  <script>
    const trainingText = document.getElementById("txa_trainingText").value;
    document.getElementById("btn_submit").addEventListener("click", inputFromText(trainingText));
    function inputFromText(text) {
      ...
    } 
  </script>
</body>

I found out that when using a function without the text argument one could solve the problem by writing:

function inputFromText(e) {
  e.preventDefault();
  ...
}
AstronAUT
  • 639
  • 2
  • 7
  • 11
  • Possible duplicate of [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – DocMax Oct 14 '17 at 16:00
  • You need to pass the reference to the function as the second parameter to `addEventListener`. As written, you are calling the function and passing the returned value instead. See the linked question for more detailed answers. – DocMax Oct 14 '17 at 16:01

2 Answers2

0

I believe you need to wrap the click event handler as a function, so line would read:

document.getElementById("btn_submit").addEventListener("click", function() { inputFromText(trainingText)});
SmokeRaven
  • 111
  • 7
  • That prevents it from getting triggered right from the start, but now when I am trying to call e. g. 'console.log(123);' in the function. "123" pops up for a short time but immediately gets deleted from the console again, thats weird... – AstronAUT Oct 14 '17 at 16:40
  • true, i think you want to look at @santoshkumar comment then and change button type to "button" instead of "submit" . . . otherwise when you look at the console output it will go away when the form posts back to the server (i.e. submit button behavior). if you really need a submit button, you can do your console.log before alert and page execution will pause until you click the alert giving you time to examine console.log – SmokeRaven Oct 15 '17 at 17:09
0

Just change the button type="submit" to button type="button"

<button type="button" class="btn btn-default" id="btn_submit">Submit</button>
Santosh Kumar
  • 1,756
  • 15
  • 24