JavaScript - 获取 HTML 表单值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3547035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:06:46  来源:igfitidea点击:

JavaScript - Getting HTML form values

javascripthtml

提问by user377419

How can I get the value of an HTML form to pass to JavaScript?

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

Is this correct? My script takes two arguments one from textbox, one from the dropdown box.

这样对吗?我的脚本需要两个参数,一个来自文本框,一个来自下拉框。

<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>

采纳答案by user406632

HTML:

HTML:

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

JS:

JS:

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

回答by Kevin Farrugia

If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use:

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

JavaScript

JavaScript

new FormData(document.querySelector('form'))

form-serialize (https://code.google.com/archive/p/form-serialize/)

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

serialize(document.forms[0]);

jQuery

jQuery

$("form").serializeArray()

回答by Tran Nguyen Nhat Thuy

Here is an example from W3Schools:

以下是 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);
}

The demo can be found here.

可以在此处找到演示。

回答by Codeacula

document.formswill contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

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];
    }
}

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

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

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

回答by Klesun

My 5 cents here, using form.elementswhich allows you to query each field by it's name, not only by iteration:

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

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

回答by Rusca8

Expanding on Atrur Klesun's idea... you can just access it by its name if you use getElementById to reach the form. In one line:

扩展 Atrur Klesun 的想法……如果您使用 getElementById 访问表单,则可以通过其名称访问它。在一行中:

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

I used it like so for radio buttons and worked fine. I guess it's the same here.

我像这样将它用于单选按钮并且工作正常。我想这里也是一样。

回答by bluejayke

Quick solution to serialize a form without any libraries

无需任何库即可序列化表单的快速解决方案

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>

回答by jhaavist

This is a developed example of https://stackoverflow.com/a/41262933/2464828

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

Consider

考虑

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

Let us assume we want to retrieve the input of name formula. This can be done by passing the eventin the onsubmitfield. We can then use FormDatato retrieve the values of this exact form by referencing the SubmitEventobject.

让我们假设我们要检索 name 的输入formula。这可以通过eventonsubmit字段中传递 来完成。然后我们可以FormData通过引用SubmitEvent对象来检索这种精确形式的值。

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

The JavaScript code above will then print the value of the input to the console.

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

If you want to iterate the values, i.e., get all the values, then see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

如果要迭代值,即获取所有值,请参阅https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

回答by Atav32

Several easy-to-use form serializers with good documentation.

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

In order of Github stars,

按照 Github 星数排序,

  1. jquery.serializeJSON

  2. jquery-serialize-object

  3. form2js

  4. form-serialize

  1. jquery.serializeJSON

  2. jquery 序列化对象

  3. 表单2js

  4. 表单序列化

回答by Randhawa

<input type="text" id="note_text" />

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