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

时间:2015-07-10 04:12:27

标签: javascript jquery html object input

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

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

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

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>

我认为JS对象看起来像是什么,每次用户按下“添加到列表”时,程序会在列表中添加另一个First / Middle / Last名称。:

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

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

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

6 个答案:

答案 0 :(得分:3)

您可以使用点击处理程序,例如

&#13;
&#13;
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)));
})
&#13;
pre {
  white-space: pre-wrap;
}
&#13;
<!-- 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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您可以从输入创建对象(因为它们在给定标记中查找),例如:

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

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

fiddle

答案 3 :(得分:0)

如果您的目标是映射每个名称的频率,则使用三个哈希可能是最有效的选项。仅作为其中一个输入的示例:

var firstNames = {};

function setFirstName(firstName){

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

function buildList(){

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

}

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

答案 4 :(得分:0)

[] {}

之间存在差异

push()方法和长度属性仅适用于 [] ,因为它实际上是JavaScript数组

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

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

如果您喜欢这样,那么您可以在按钮点击事件中进行编码

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

答案 5 :(得分:0)

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

&#13;
&#13;
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)));
})
&#13;
pre {
  white-space: pre-wrap;
}
&#13;
<!-- 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>
&#13;
&#13;
&#13;