簡體   English   中英

使用jQuery將表單元素動態添加到動態表單

[英]Dynamically adding form elements to dynamic form using jquery

我遵循此示例如何使用jQuery動態添加表單元素

是否可以將表單元素動態添加到動態生成的表單中?

這是我的代碼:

<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添加到動態添加的表單的底部,但是什么也沒有發生。

有兩個具體問題。

  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 }); 

我整理了一個包含以上詳細說明的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM