TL;DR: Is there a way to pass what a HTML form submits as an object to a JavaScript function?
In a form like this one:
<form action="javascript:myFunction(this);" name="myForm">
<label>First: <input type="text" name="first"></label>
<label>Second: <input type="text" name="second"></label>
<input type="submit" value="Submit this to Javascript!">
</form>
I want to pass the values of the form's inputs to a JavaScript function myFunction, instead of sending them to some other page with action (as in this line here: action="sendToPHPPage.php").
So far, my best attempt was to get all elements from the form, like this:
function myFunction(formThis) {
let form = document.getElementsByName('myForm')[0];
inputs = form.getElementsByTagName('input');
for (let x of inputs) //do something with x.value
console.log(formThis);
}
What I wanted, though, was that the this in myFunction(this) would allow me directly work on the inputs of the form. So instead of using document.getElementsByName('myForm') I could simply work on the this argument. But console.log(thisForm) tells me that formThis === window. That is, this gets me the window object.
Question: How can I make the this be binded to the form -- that is, how can I make the this argument represent the form or become an object that has as keys each one of the inputs? Is this possible without using document.get... || document.querySelector...?
Related SO questions: How do I get the value of text input field using JavaScript? , Passing HTML input value as a JavaScript Function Parameter
submitevent? If so you can get access to the form using theevent.currentTargetinside the callback whereeventis the passed argument to the callbackonlickattribute to submit, oy maybe changing it to atype="button"like here: java2s.com/Code/JavaScript/Language-Basics/… . I'm gonna try that nowsubmitevent because the form can be submitted in multiple ways via mouse or keyboard, in order to not trying to catch different cases you can usesubmitevent which will get do this unnecessary work for you. Also if you go withclicklistener theevent.currentTargetwill be the button which seem like not what you want from the descriptionactionattribute from form (that is, now form is just<form name="myForm">) and changed the type of the submit button totype="button"and then addedonclick="myFunction(this.form)"I get:TypeError: myFunction is not a function. But I can call myFunction and it is clearly a function. What's wrong here?addEventListenergives you a passed event as well as an option to remove the event listener when needed, while inlining these makes it not as streamlined, however this can be my personal preference.