【问题标题】:Js to duplicate section of fields and rename for form submissionJs复制字段部分并重命名表单提交
【发布时间】:2020-03-22 01:27:25
【问题描述】:

我需要向表单页面动态添加字段,以便用户可以添加相同表单的其他条目。它是一种描述细分中单元的形式,单元的数量和类型各不相同。我需要使用 js 添加一个加号按钮,这将允许他们添加字段,并且我想这些字段名称要递增,所以它们都是处理程序的单独输入。我对html的内容如下

   <!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="exhibitb.css" rel="stylesheet">
    <meta charset="utf-8">
    <title>Chicago Low-Income Housing Trust Fund</title>
  </head>
  <body>

      <form action="/clihtf.php" method="post">
        <div class="bold2">  Exhibit B</div>
        <div class="bold"> DSU</div>
             <section>
  <p>
        <span>unit: </span>
        <br>
      </label>
      <input type="number" id="totUni" name="totUni" >
          <p>
      <label for="nbr">
        <span>nbr: </span>  
      </label>
             <br>
      <input type="number" id="nbr" name="nbr" >
    </p>
          <p>
      <label for="trsu">
        <span>trsu: </span>  
      </label>
             <br>
      <input type="number" id="trsu" name="trsu">
    </p>
          <p>
      <label for="mtpr">
        <span>Mtpr: </span>  
      </label>
             <br>
      <input type="text" id="mtpr" name="mtpr">
    </p>
          <p>
      <label for="msasu">
        <span>Monthly SAU: </span>  
      </label>
             <br>
      <input type="text" id="msasu" name="msasu">
      <p>
      <label for="ssfga">
        <span>Social SOP (Exhibit F):
          <br> </span>  
      </label>
             <br>
      <input type="text" id="ssfga" name="ssfga">
               <p>
                  <label for="ssfgb">
    Social Service Plan (Exhibit G):
                    <br>
  <input type="text" id="ssfgb" name="ssfgb">

        <p> <button type="submit" value="submit">Submit</button> </p>
           </form>
  </body>

我已经尝试过这里显示的内容:Adding input fields in Javascript with onclick buttonHow to create a minus and plus button to update a field? 但我就是不明白。我只需要从字面上复制所有字段,然后让它们以不同的名称提交。如果这要求太多,我很抱歉。

【问题讨论】:

  • 使用 jQuery 方法应该更容易。你能把它添加到你的项目中吗?
  • 是的,用 jquery 就可以了。如果有人可以向我解释整个事情,我会理解前进

标签: javascript html


【解决方案1】:

首先你必须用 /section 来关闭 section 标签,例如在 /form 之前。

然后你可以试试这样的:

var a = $('form section'); // get the section of the form
var b = $(a[0].innerHTML); // get the components to duplicate
b.find('[id]').get().forEach(e => $(e).attr('id', $(e).attr('id') + '_1')); // set "ids" of new components
b.find('[name]').get().forEach(e => $(e).attr('name', $(e).attr('name') + '_1')); // set "names"
b.find('[for]').get().forEach(e => $(e).attr('for', $(e).attr('for') + '_1')); // set "fors"
b.find('button').remove(); // do not copy the submit button
$('form section').append(b); // add new components to the section of the form

以该示例为基础,因为它仅适用于一组新组件,您必须对其进行调整以进行更多(或更好)实施。

【讨论】:

  • 非常有帮助,谢谢eddi。这完美地回答了我找到的另一个版本的问题,给了我另一个不同变量的例子,从而概述了我需要改变或适应的地方!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
相关资源
最近更新 更多