【问题标题】:Concat Form Field Values连接表单字段值
【发布时间】:2020-11-10 00:09:16
【问题描述】:

希望我无论如何都不会重复这个问题。但我试图获得一个表单部分,其名称值和字段值作为单个连接字符串。很喜欢

表单输入:
名字:约翰
姓氏:史密斯
字段 5 - 10.. 等

字符串输出: FirstName=John&LastName=Smith&Field2=Value2&Field_etc=Value_etc

我试过了

      var inputArray = $("form#form :input").each(function () {
        var input = $(this);
        console.log(input.attr('name') + ":" + input.val()); 
      });

哪个在console.log中正确输出测试值

名字:约翰
姓:史密斯

但我正在努力编写下一段代码来帮助 console.log 将它作为一个组合数组字符串。不确定这是 for 循环 还是有助于下一步的东西。

【问题讨论】:

    标签: html jquery forms


    【解决方案1】:

    请参阅下面代码中的 cmets,也许这可能会帮助您走上正轨...

    这里最酷的是将提交数据存储为一个对象,然后使用$.param()将提交转换为url字符串。

    // on form submit
    $(document).on('submit', '#form', function(e) {
    
      // prevent form default submit action
      e.preventDefault();
    
      // set empty submission object
      let submission = {};
    
      // for each of this form submit event target object entries as key/field
      for (const [key, field] of Object.entries(e.target)) {
    
        // if object entry (field) has a name attribute
        if (field.name) {
    
          // add name/value to submission object
          submission[field.name] = field.value;
    
        }
    
      }
      
      // convert submission object to url params string
      var paramsStr = $.param( submission );
    
      // log the string
      console.log(paramsStr)
    
    });
    <form id="form">
      <input name="firstName" value="John" type="text" />
      <input name="lastName" value="Smith" type="text" />
      <input name="userName" value="johnsmith" type="text" />
      <button type="submit">Submit</button>
    </form>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      【解决方案2】:

      遍历输入元素并连接名称和值:

      const inputs = document.querySelectorAll('#form input')
      let msg
      
      inputs.forEach(inp => {
        inp.onkeyup = () => {
          msg = 'String Output: '
          inputs.forEach(i => msg += `${i.name}=${i.value}&`)
          console.clear() 
          console.log(`\r\n${msg.slice(0, -1)}\r\n\r\n`)
        }
      })
      input {
        display: block;
        margin-bottom: 8px;
        font:18px/1.2em Arial; 
      }
      <form id='form'>
        <input name='FirstName' placeholder='First Name' />
        <input name='LastName' placeholder='Last Name' />
        <input name='Example1' placeholder='Example 1' />
        <input name='Example2' placeholder='Example 2' />
      </form>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-02
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 2013-01-04
        • 1970-01-01
        • 2014-10-31
        • 2012-01-05
        相关资源
        最近更新 更多