gpt4 book ai didi

javascript - 如何克隆没有值的表单字段?

转载 作者:行者123 更新时间:2023-12-03 07:10:34 24 4
gpt4 key购买 nike

如何在不保留字段值的情况下克隆以下 html?

<form method=POST action="/url">
<div class="form-group" data-answer>
<div class="pull-left"><label><input type="checkbox" name="answer[1][is_correct]" value="true"> Correct Answer</label></div>

<div class="pull-right">
<a href="#" data-remove><span class="glyphicon glyphicon-remove"></span></a>
</div>
<input type="text" class="form-control" name="answer[1][body]" placeholder="Possible answer">
</div>

<div class="form-group" data-answer>
<div class="pull-left"><label><input type="checkbox" name="answer[2][is_correct]" value="true"> Correct Answer</label></div>

<div class="pull-right">
<a href="#" data-remove><span class="glyphicon glyphicon-remove"></span></a>
</div>
<input type="text" class="form-control" name="answer[2][body]" placeholder="Possible answer">
</div>

. . .

<button type="submit">Submit</button>
</form>

我在这里只能看到 3 个可能的选择。然而,它们都存在重大缺陷:

  1. .clone() .form-field 正常并重置字段值。
    问题:一一重置所有值非常麻烦,而且不是面向 future 的解决方案。例如,如果.form-group中添加了更多字段,则需要单独清除它们的值。
  2. 在页面上包含隐藏的 .form-group 作为模板。
    问题:如您所见,输入字段包含枚举名称,例如:answer[1][body]。克隆最后一个 .form-group 并将值加 1 很方便。克隆模板化的 .form-group 将缺乏这种灵 active 。
  3. 以原始 html 形式读取字段并将其转换为 JQuery 对象
    问题:这对我来说似乎是一个明确的解决方案,但我无法让它发挥作用。代码 $.parseHTML($('.form-group').html()) 未返回有效的 JQuery 对象,我需要使用 .find() > 以及其他方法。

什么是解决这个问题的有效且优雅的解决方案?

最佳答案

试试这个代码:

 $("button").click(function(){
var t = $("form").clone().appendTo("#clonedForm");
$(t).find("input[type=checkbox],input[type=text], textarea").removeAttr("checked").val('');
});

关于javascript - 如何克隆没有值的表单字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com