我有一个网页,到处都有多种表单,在一些页面中,一次有4或5个表单。此时,我获得了表单输入字段针对其特定名称的内容(使用jQuery):
html
<input id="lastname" name="lastname" type="text" class="form-control" placeholder="Last name*">js
var lastname = $("[name='lastname']").val();尽管如此,这是不可伸缩的,我需要在每次添加更多的HTML表单时添加更多的变量,这些表单的名称都是唯一的(所有的表单都与相同的4个字段一致)。我想实现一个vanilla javascript函数,当按submit按钮时,它可以处理所有表单--我现在是这样做的:
//At this momment I get the values using jQuery, targeting the specific input name:
$('.btn').click(function(){
$('.btn').attr("disabled", true);
var name = $("[name='name']").val();
var lastname = $("[name='lastname']").val();
var phone = $("[name='phone']").val();
// make a var for every input field known
//stuff to send it via ajax to an external api:
/*
{ ... }
*/
}<form>
<label for="name">Name*</label>
<input type="text" placeholder="name here" id="name" name="name" required>
<label for="lastname">Last Name*</label>
<input type="text" placeholder="last name here" id="lastname" name="lastname" required>
<label for="phone">Phone Number*</label>
<input type="text" placeholder="phone # here" id="phone" name="phone-2" required>
<button class="btn" onclick="process()">Submit</button>
</form>
<form>
<label for="name-2">Name*</label>
<input type="text" placeholder="name here" id="name-2" name="name-2" required>
<label for="lastname-2">Last Name*</label>
<input type="text" placeholder="last name here" id="lastname-2" name="lastname-2" required>
<label for="phone-2">Phone Number*</label>
<input type="text" placeholder="phone # here" id="phone-2" name="phone-2" required>
<button class="btn" onclick="process()">Submit</button>
</form>
<form>
<label for="name">Name*</label>
<input type="text" placeholder="name here" id="name-3" name="name-3" required>
<label for="lastname">Last Name*</label>
<input type="text" placeholder="last name here" id="lastname-3" name="lastname-3" required>
<label for="phone">Phone Number*</label>
<input type="text" placeholder="phone # here" id="phone-3" name="phone-3" required>
<button class="btn" onclick="process()">Submit</button>
</form>
我希望只有一个javascript函数接收整个表单(当单击按钮时),并在内部遍历表单元素以获取字段的值,这样,它就可以重用到所有的窗体中。
发布于 2022-02-14 23:03:23
javascript函数应该首先接收元素,然后遍历到父元素:
<form>
<label for="name">Name*</label>
<input type="text" placeholder="name here" id="name" name="name" required>
<label for="lastname">Last Name*</label>
<input type="text" placeholder="last name here" id="lastname" name="lastname" required>
<label for="phone">Phone Number*</label>
<input type="text" placeholder="phone # here" id="phone" name="phone-2" required>
<button class="btn" onclick="process(this)">Submit</button>
</form>使用按钮中的onclick="process( this )“,它将调用与之关联的javascript函数,并发送单击所在的元素。
js
process(element){
var form = element.closest('form')
// now you can extract the input field of this specific form.
}现在您可以根据需要使用:Get all the elements of a particular form获取输入字段。
https://stackoverflow.com/questions/71117836
复制相似问题