【问题标题】:Dynamic input field gets removed automatically in a form [duplicate]动态输入字段在表单中自动删除[重复]
【发布时间】:2020-11-30 03:49:09
【问题描述】:

请参考图片

  1. 我正在尝试编写一个“+”按钮,当您单击它时,我的 Jquery 会动态添加另一个大小输入字段

  2. 问题是当它在“form”标签内并且我点击按钮时,它会出现 1 秒钟然后自动消失。当我删除“表单”标签时,它会按预期工作并且不会消失。

这是导致问题的大小输入代码的一部分:

<form method="POST" action="addProduct.php">
   <div class="col-lg-4 topmargin">
   <span><h4>Size</h4></span>
   <table class="table borderless sizeTable" id="dynamic_price" >
      <tr>
        <td> <input class="form-control "type="text" name="size[]" placeholder="200 ml" size="100%"> </td> 
        <td><button  class="btn btn-primary" name="addSize" id="addSize">+</button></td>
      </tr>
  </table>
</div>
</form>

这里是 JQuery:

   <script> 
    
    $("#addSize").click(function(){
        $('.sizeTable tbody tr:last').after('<tr><td> <input class="form-control "type="text" name="size[]"  placeholder="9.99" size="100%"> </td><td><button  class="btn btn-danger" name="removeSize">-</button></td></tr>');
    });
    </script>

如何让它在我的表单中工作?

【问题讨论】:

  • 您似乎错过了在您的帖子中包含图片。使用edit
  • 谢谢你,我刚刚把它们包括在内
  • 你的button必须是button type="button"(否则会被定义为提交,在这种情况下你需要设置e.preventDefault()
  • 你能把它放在答案中吗,有一个运行的例子,我认为它会有所帮助

标签: javascript html jquery forms html-table


【解决方案1】:

您的button 需要有type="button",否则默认为type="submit"。如果您想保留type="submit"(暂时),您需要在事件侦听器上使用preventDefault(),以防止它在表单上执行默认的“提交”操作。

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多