获取 HTML 表单值

如何获得传递给 JavaScript 的 HTML 表单的值?

我的脚本有两个参数,一个来自文本框,一个来自下拉框。

<body>
<form name="valform" action="" method="POST">


Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
Card Type: <select name="cardtype" id="cardtypeid">
<option value="visa">Visa</option>
<option value="mastercard">MasterCard</option>
<option value="discover">Discover</option>
<option value="amex">Amex</option>
<option value="diners">Diners Club</option>
</select><br/>
<input type="button" name="submit" value="Verify Credit Card" onclick="isValidCreditCard(document.getElementById('cctextboxid').value,document.getElementById('cardtypeid').value)" />
</body>
789254 次浏览

HTML:

<input type="text" name="name" id="uniqueID" value="value" />

约翰逊:

var nameValue = document.getElementById("uniqueID").value;

document.forms将在页面上包含一个表单数组。您可以循环遍历这些表单,以找到所需的特定表单。

var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
if(form.id == "wanted_id") {
form = document.forms[i];
}
}

每个表单都有一个元素数组,然后可以通过该数组循环查找所需的数据。您还应该能够通过名称访问它们

var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);

以下是 W3Schools 的一个例子:

function myFunction() {
var elements = document.getElementById("myForm").elements;
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.name] = item.value;
}


document.getElementById("demo").innerHTML = JSON.stringify(obj);
}

演示可以找到 给你

如果要检索表单值(比如那些将使用 HTTP POST 发送的值) ,可以使用:

JavaScript

function getData(form) {
var formData = new FormData(form);


// iterate through entries...
for (var pair of formData.entries()) {
console.log(pair[0] + ": " + pair[1]);
}


// ...or output as an object
console.log(Object.fromEntries(formData));
}


document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault();
getData(e.target);
});

例子: https://codepen.io/kevinfarrugia/pen/Wommgd?editors=1111


或者你可以使用以下不太推荐的选项:

表单序列化(https://code.google.com/archive/p/form-serialize/)

serialize(document.forms[0]);

JQuery

$("form").serializeArray()
<input type="text" id="note_text" />


let value = document.getElementById("note_text").value;

几个易于使用的表单序列化器,具有良好的文档。

按照 Github 星排序,

  1. 序列化

  2. 序列化对象

  3. 表格2

  4. 表单序列化

我的5美分在这里,使用 form.elements,它允许你通过 name查询每个字段,而不仅仅是通过迭代:

const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;

扩展 Atrur Klesun 的想法... 如果你使用 getElementById 到达表单,你可以直接通过它的名字访问它。一句话:

document.getElementById('form_id').elements['select_name'].value;

我用它来做单选按钮,效果很好。我想这里也是一样。

不使用任何库序列化窗体的快速解决方案

function serializeIt(form) {
return (
Array.apply(0, form.elements).map(x =>
(
(obj =>
(
x.type == "radio" ||
x.type == "checkbox"
) ?
x.checked ?
obj
:
null
:
obj
)(
{
[x.name]:x.value
}
)
)
).filter(x => x)
);
}


function whenSubmitted(e) {
e.preventDefault()
console.log(
JSON.stringify(
serializeIt(document.forms[0]),
4, 4, 4
)
)
}
<form onsubmit="whenSubmitted(event)">
<input type=text name=hiThere value=nothing>
<input type=radio name=okRadioHere value=nothin>
<input type=radio name=okRadioHere1 value=nothinElse>
<input type=radio name=okRadioHere2 value=nothinStill>


<input type=checkbox name=justAcheckBox value=checkin>
<input type=checkbox name=justAcheckBox1 value=checkin1>
<input type=checkbox name=justAcheckBox2 value=checkin2>


<select name=selectingSomething>
<option value="hiThere">Hi</option>
<option value="hiThere1">Hi1</option>
<option value="hiThere2">Hi2</option>
<option value="hiThere3">Hi3</option>
</select>
<input type=submit value="click me!" name=subd>
</form>

这是 https://stackoverflow.com/a/41262933/2464828的一个开发示例

考虑一下

<form method="POST" enctype="multipart/form-data" onsubmit="return check(event)">
<input name="formula">
</form>

假设我们希望检索名称 formula的输入。这可以通过在 onsubmit字段中传递 event来完成。然后,我们可以使用 FormData通过引用 SubmitEvent对象来检索这个精确表单的值。

const check = (e) => {
const form = new FormData(e.target);
const formula = form.get("formula");
console.log(formula);
return false
};

然后,上面的 JavaScript 代码将输出输入的值到控制台。

如果您想迭代这些值,也就是说,获取所有的值,那么请参见 https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

请尝试更改以下代码:

<form
onSubmit={e => {
e.preventDefault();
e.stopPropagation();


const elements = Array.from(e.currentTarget);


const state = elements.reduce((acc, el) => {
if (el.name) {
acc[el.name] = el.value;
}


return acc;
}, {});


console.log(state); // {test: '123'}
}}
>
<input name='test' value='123' />
</form>

这就是你问题的答案。

可以使用 this.<<name of the field>>.value将表单字段的值传递给函数。

并将输入提交改为按钮提交。从表单调用函数。

<body>
<form name="valform" method="POST" onsubmit="isValidCreditCard(this.cctextbox.value, this.cardtype.value)">
Credit Card Validation: <input type="text" id="cctextboxid" name="cctextbox"><br/>
Card Type:
<select name="cardtype" id="cardtypeid">
...
</select>
<br/>
<button type="submit">Verify Credit Card</button>
</body>

从技术上讲,你可以在你的函数中使用 document.getElementById("cctextboxid"),但是他的解决方案是简洁和简单的代码。

我知道这是一个旧的职位,但也许有人在线可以使用这一点。

// use document.form["form-name"] to reference the form
const ccForm = document.forms["ccform"];


// bind the onsubmit property to a function to do some logic
ccForm.onsubmit = function(e) {


// access the desired input through the var we setup
let ccSelection = ccForm.ccselect.value;
console.log(ccSelection);


e.preventDefault();
}
<form name="ccform">
<select name="ccselect">
<option value="card1">Card 1</option>
<option value="card2">Card 2</option>
<option value="card3">Card 3</option>
</select>
<button type="submit">Enter</button>
</form>

<form id='form'>
<input type='text' name='title'>
<input type='text' name='text'>
<input type='email' name='email'>
</form>
const element = document.getElementByID('#form')
const data = new FormData(element)
const form = Array.from(data.entries())
/*
form = [
["title", "a"]
["text", "b"]
["email", "c"]
]
*/
for (const [name, value] of form) {
console.log({ name, value })
/*
{name: "title", value: "a"}
{name: "text", value: "b"}
{name: "email", value: "c"}
*/
}

我发现这是最优雅的解决方案。

function handleSubmit(e) {
e.preventDefault();
const formData = new FormData(e.target);
const formProps = Object.fromEntries(formData);
}
<script>
var inputs = document.getElementById("form_id_here").elements;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type === "text" || inputs[i].type === "textarea") {
console.log(inputs[i].value); // Get value of input tag which you have entered.
}
}
</script>

上面的一些答案并不适合具有相同名称的多个字段的表单,例如,多个 <input name="categories[]">,所以我很快就做出了这个答案。它期望字段的名称与您希望作为数组收集的名称相同,以 []作为约定结束,但是可以进行更新以处理其他场景。

function getFormValues(form) {
const formData = new FormData(form);
return Array.from(formData.entries()).reduce((prev, [inputName, val]) => {
return {
...prev,
[inputName]: inputName.endsWith('[]')
? prev[inputName]
? [...prev[inputName], val]
: [val]
: val,
};
}, {});
}


// alternative if you don't like reducers and nested ternary statements
function getFormValues(form) {
const formData = new FormData(form);
const values = {};
for (const [inputName, val] of formData.entries()) {
if (inputName.endsWith('[]')) {
values[inputName] = values[inputName] ? [...values[inputName], val] : [val];
} else {
values[inputName] = val;
}
}
return values;
}


// then attach this to form submit
function onSubmit(e) {
e.preventDefault();
const values = getFormValues(e.target);
// etc...
}
     

值给出类似 { "single": "something", "categories[]": ["one", "two"] }的值

使用 for-of 循环很容易,您可以获得所有字段值,甚至复选框值也是如此。

在 HTML 中,应该在表单 onsubmit事件上绑定 handlSubmit()

<form name="contact_form"
id="contact-form"
class="form-controller"
onsubmit="handleSubmit(event)"
>

在您的 javascript 中,不管您为字段分配了什么名称,您的代码都应该应用以下逻辑。

const handleSubmit = (event)=> {
event.preventDefault();


const formData = new FormData(event.target);
formObj = {};
    

for (const [fieldName] of formData) {
const fieldValue = formData.getAll(fieldName);
formObj[fieldName] = fieldValue.length == 1 ? fieldValue.toString() : fieldValue
}
console.log('formObj',formObj)
}

ES6的一行程序

getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector)))


console.log('Output of getFormData:')
console.log(getFormData('#myTargetForm'))
<!DOCTYPE html>
<html>
<body>


<h2>Get Form Data as Javascript Object</h2>


<form id="myTargetForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

在 Javascript 中定义这个函数:

getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector)))

然后调用任何选择器,例如: getFormData('#myTargetForm')