【问题标题】:How to store HTML form input as JavaScript Object如何将 HTML 表单输入存储为 JavaScript 对象
【发布时间】:2015-09-28 16:53:39
【问题描述】:

我正在自学 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 对象的样子,每次用户按下“添加到列表”时,程序都会在列表中添加另一个名字/中间名/姓氏。:

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'

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

【问题讨论】:

  • @bassxzero 代码不错,但是不需要在隐藏输入中保存对象,可以使用全局变量。
  • @shyammakwana.me 我知道这一点,但考虑到 OP 无法理解客户端数据的存储位置/方式,我想让它尽可能清晰/简单。不过还是谢谢
  • @bassxzero 是的!就这样!!非常感谢你写了这篇文章并向我展示了它是如何工作的。现在我只需要检查它并了解它的工作原理和原因,以便我可以像你一样掌握它!我敢肯定,一旦掌握了它的要点,它就非常简单。非常感谢!
  • @shyammakwana.me -- “隐藏输入”是什么意思?谢谢!!

标签: javascript jquery html object input


【解决方案1】:

您可以使用类似的点击处理程序

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>

【讨论】:

  • 任何人都可以在没有 JQuery 的情况下为我提供相同的逻辑。在简单的 JS 对象中。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

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

      function buildList(){
              var list = {};
              $("body").find("input").each(function() {
      
                  var field= $(this).attr('id');
                  var value= $(this).val();
                  list[field] = value;
              });
      }
      

      fiddle.

      【讨论】:

      • 在他的应用程序中,每次按下按钮时都会覆盖 firstName 属性值,而不是将其添加到列表中并保持计数。
      【解决方案5】:

      []{} 之间有区别

      push() 方法和 length 属性只适用于 [] 因为它实际上是 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
      });
      

      【讨论】:

        【解决方案6】:

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

        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>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多