如何将 HTML 表单输入存储为 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31332316/
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 06:32:22  来源:igfitidea点击:

How to store HTML form input as JavaScript Object

javascriptjqueryhtmlobjectinput

提问by jward01

I am self learning JS and working on an exercise which takes input from the user(First Name, Middle Name, Last Name), and saves the input in a JS Object (Later I will manipulate the object itself and sort it, check duplicates, etc.)

我正在自学 JS 并进行一项练习,该练习接受用户的输入(名字、中间名、姓氏),并将输入保存在 JS 对象中(稍后我将操作对象本身并对其进行排序,检查重复项,等等。)

I have looked everywhere and cannot find any direction on this one. I am familiar with saving HTML input as variables (var n=document.getElementById('x').value) but I am very new to objects.

我到处找,找不到任何方向。我熟悉将 HTML 输入保存为变量 (var n=document.getElementById('x').value) 但我对对象很陌生。

How would I save user input in objects? And can I save multiples 'submissions' in the Object as in 'load the object up from user input', and then manipulate it on a later step?

我如何将用户输入保存在对象中?我是否可以像在“从用户输入中加载对象”那样在对象中保存多个“提交”,然后在稍后的步骤中对其进行操作?

HTML:

HTML:

<body>
  <label>First Name:
    <input type='text' name='firstName' id='firstName' placeholder="First Name">
  </label>
  <br>
  <br>
  <label>Middle Name:
    <input type='text' name='middleName' id='middleName' placeholder="Middle Name">
  </label>
  <br>
  <br>
  <label>Last Name:
    <input type='text' name='lastName' id='lastName' placeholder="Last Name">
  </label>
  <br>
  <br>
  <button type="button" onclick="buildList()">Add to List</button>
</body>

What I imagine the JS Object to look like, and each time the user presses 'Add to List' the program adds another First/Middle/Last name to the list.:

我想象 JS 对象的样子,每次用户按下“添加到列表”时,程序都会向列表中添加另一个名字/中间名/姓氏。:

var list = {
    firstName:"John",
    middleName:"Will",
    lastName:"Doe"
},
{
    firstName:"Ben",
    middleName:"Thomas",
    lastName:"Smith"
},
{
    firstName:"Brooke",
    middleName:"James",
    lastName:"Kanter"
};

***Note, later on I plan to count the frequency of each First/Middle/Last Name and output it on the screen.. i.e.: 'FirstName'Jason: 2, 'FirstName'Ed:3; 'MiddleName'Marie:5; 'LastName'Smith:3'

***注意,稍后我计划计算每个名字/中间名/姓氏的频率并将其输出到屏幕上..即: 'FirstName'Jason: 2, 'FirstName'Ed:3; 'MiddleName'Marie:5; 'LastName'Smith:3'

My goal: Create a list of full names. Break them out into three lists: first, middle, and last names. Count the frequency of the names in each list. ---I figured using an object would be the best way to do this.

我的目标:创建一个全名列表。将它们分成三个列表:名字、中间名和姓氏。计算每个列表中名称的频率。---我认为使用对象是最好的方法。

采纳答案by Arun P Johny

You could use a click handler like

你可以使用像这样的点击处理程序

var list = [],
  $ins = $('#firstName, #middleName, #lastName'),
  counter = {
    firstName: {},
    middleName: {},
    lastName: {}
  };
$('#add').click(function() {
  var obj = {},
    valid = true;
  $ins.each(function() {
    var val = this.value.trim();
    if (val) {
      obj[this.id] = val;
    } else {
      var name = this.previousSibling.nodeValue.trim();
      alert(name.substring(0, name.length - 1) + ' cannot be blank');
      this.focus();
      valid = false;
      return false;
    }
  });
  if (valid) {
    list.push(obj);
    $ins.val('');

    $.each(obj, function(key, value) {
      var count = counter[key][value] || 0;
      counter[key][value] = count + 1;
    });

  }
});

$('#print').click(function() {
  $('pre').text(JSON.stringify(list) + '\n\n');
  $('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
  white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
  <input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
  <input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
  <input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>

<pre></pre>

回答by Mark E

Js objects are very easy to manipulate (which many times makes it prone to more errors). If you want to add a property just put some value on it.

Js 对象非常容易操作(这很多时候容易出现更多错误)。如果你想添加一个属性,只需在它上面放一些值。

var info = {};//create an empty object
info.firstName = document.getElementById('firstName').value;
info.lastName = document.getElementById('lastName').value;
allInfo.push(info);//you had to initialize the array before

回答by Adib Aroui

You could create an object from the inputs (as they look in given markup), like:

您可以从输入创建一个对象(正如它们在给定标记中的样子),例如:

function buildList(){
        var list = {};
        $("body").find("input").each(function() {

            var field= $(this).attr('id');
            var value= $(this).val();
            list[field] = value;
        });
}

fiddle.

小提琴

回答by Ryan Neuffer

If your goal is to map the frequency of each name, using three hashes might be the most efficient option. As an example for just one of the inputs:

如果您的目标是映射每个名称的频率,则使用三个散列可能是最有效的选择。作为输入之一的示例:

var firstNames = {};

function setFirstName(firstName){

    if(firstNames[firstName] === undefined){
        firstNames[firstName] = 1;
        return;
    }
    firstNames[firstName]++;
}

function buildList(){

    setFirstName(document.getElementById('firstName').value);

}

That way you'll end up with something like var firstNames = {tom: 3, dick: 10, harry: 2, ...}. Here's a fiddle: https://jsfiddle.net/n3yhu6as/2/

这样你最终会得到类似的东西var firstNames = {tom: 3, dick: 10, harry: 2, ...}。这是一个小提琴:https: //jsfiddle.net/n3yhu6as/2/

回答by Dickens A S

There is a difference between []and {}

[]{}之间有区别

The push()method and lengthproperty is only applicable to []becuase it actually the JavaScript array

所述推送()方法和长度特性仅适用于[] ,原因是其实际的JavaScript数组

Therefore in your case you should put your JSON Object inside a JSON Array

因此,在您的情况下,您应该将 JSON 对象放在 JSON 数组中

var list = [{
    firstName:"John",
    middleName:"Will",
    lastName:"Doe"
},
{
    firstName:"Ben",
    middleName:"Thomas",
    lastName:"Smith"
},
{
    firstName:"Brooke",
    middleName:"James",
    lastName:"Kanter"
}];

If you do like this then you do code in your button click event as

如果你喜欢这个,那么你在你的按钮点击事件中做代码

list.push({
    firstName: document.getElementById("firstName").value,
    middleName: document.getElementById("middleName").value,
    lastName: document.getElementById("lastName").value
});

回答by gaan10

how to search for a particular keyword from the user provided name fields.

如何从用户提供的名称字段中搜索特定关键字。

var list = [],
  $ins = $('#firstName, #middleName, #lastName'),
  counter = {
    firstName: {},
    middleName: {},
    lastName: {}
  };
$('#add').click(function() {
  var obj = {},
    valid = true;
  $ins.each(function() {
    var val = this.value.trim();
    if (val) {
      obj[this.id] = val;
    } else {
      var name = this.previousSibling.nodeValue.trim();
      alert(name.substring(0, name.length - 1) + ' cannot be blank');
      this.focus();
      valid = false;
      return false;
    }
  });
  if (valid) {
    list.push(obj);
    $ins.val('');

    $.each(obj, function(key, value) {
      var count = counter[key][value] || 0;
      counter[key][value] = count + 1;
    });

  }
});

$('#print').click(function() {
  $('pre').text(JSON.stringify(list) + '\n\n');
  $('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
  white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
  <input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
  <input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
  <input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>

<pre></pre>