【问题标题】:Dynamically adding form elements to dynamic form using jquery使用jquery将表单元素动态添加到动态表单
【发布时间】:2013-10-10 16:10:32
【问题描述】:

我按照这个例子 How to use jQuery to add form elements dynamically

是否可以在动态生成的表单中动态添加表单元素?

这是我的代码:

<html>
 <script src="jquery.js" type="text/javascript"></script>
 <script>
 $(document).ready(function () {
     $('#addRow').click(function () {
         $('<div/>', {
            'class' : 'extraPerson', html: GetHtml()
         }).hide().appendTo('#container').slideDown('slow');
     });
     $('#addAttribte').click(function () {
         $('<div/>', {
            'class' : 'extraAttribute', html: GetHtml1()
         }).hide().appendTo('#extraAttribute').slideDown('slow');
     });
 })
 function GetHtml() {
     var len = $('.extraPerson').length;
     var $html = $('.extraPersonTemplate').clone();
     $html.find('[name=firstname]')[0].name="firstname" + len;
     return $html.html();    
 }
 function GetHtml1() {
     var len = $('.extraAttribute').length;
     var $html = $('.extraAttributeTemplate').clone();
     $html.find('[name=attribute]')[0].name="attribute" + len;
     return $html.html();    
 }
</script>
<div class="extraPersonTemplate">
    <input class="span3" placeholder="First Name" type="text" name="firstname">
    <a href="javascript:void(0)" id="addAttribute">Add Attribute</a>
    <div id="extraAttribute"></div>
</div>
<div class="extraAttributeTemplate">
    <input class="span3" placeholder="Attribute" type="text" name="attribute">
</div>
<div id="container"></div>
<a href="#" id="addRow"><i class="icon-plus-sign icon-white"></i> Add another family member</p></a>
</html>

我意识到新添加的表单元素的名称会有问题,但此时我只想能够动态地将一行文本添加到动态生成的表单中。

编辑:抱歉,忘了说问题所在;该页面以“添加另一个家庭成员”的链接开始。这将添加extraPersonTemplate。此模板还有一个“添加属性”链接,可向此新添加的字段添加一个额外的表单字段。

但是,当我单击“添加属性”时,我希望它会将 extraAttributeTemplate 添加到动态添加的表单的底部,但没有任何反应。

【问题讨论】:

  • 是的,这是可能的。只需确保动态表单存在,然后再尝试添加即可。,
  • 动态添加表单元素后,您可以像一直存在一样访问它。 DOM 上的操作并不关心元素来自哪里。
  • 如果您的代码有问题,请描述它,我们或许可以帮助您解决问题。
  • 嗨,谢谢,我已经添加了我一直看到的实际问题。

标签: javascript jquery html forms


【解决方案1】:

有两个具体问题。

  1. ID 应该是唯一的。每个人都有一个 ID 为 addAttribute 的锚点是无效的,只有在 DOM 中找到的第一个元素才会绑定事件。一开始这不是问题,因为只有其中一个,但是一旦您开始添加其他家庭成员,这确实会成为问题。

  2. 就绪处理程序中绑定的事件仅绑定到代码执行时存在的元素。如果您要添加新元素并希望绑定这些事件,您需要使用事件委托

    $(document).on('click', '.addAttribute', function() {
        // add an attribute here
        // I've changed from an ID to a class selector
        // you'll need to find a way to get a reference to the correct elements from a specific anchor
    });
    

我已将demo 与上面详述的更改放在一起。

【讨论】:

    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多