将表单输入传递给JavaScript函数(Pass form inputs to JavaScript function)

系统教程 行业动态 更新时间:2024-06-14 16:57:40
将表单输入传递给JavaScript函数(Pass form inputs to JavaScript function)

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

更多推荐

本文发布于:2023-04-13 12:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/8c5b8e791d7904eb6742d7072f69ac22.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   函数   JavaScript   Pass   inputs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!