TL; DR:有没有办法将HTML表单作为对象提交给JavaScript函数?
在这样的形式:
<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>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
更多推荐
发布评论