单击按钮添加新的fieldset元素

时间:2011-03-15 17:33:46

标签: javascript

使用JavaScript可以通过单击按钮生成字段集中的所有元素吗?下面的代码显示了一个字段集中的两个文本框和一个textarea。当我按下“添加项目按钮”时,我想在该字段集中生成相同的文本框和文本区域。

非常感谢你的帮助。

<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<p>Item                     <input type ="text" size="25"   name="prof_item" /><br /></p>
<p>Duration                 <input type ="text" size="25"   name="prof_duration" /><br /></p>
<p>Enlargement              <label for="enlargement"></label><p></p>
                            <textarea name="textarea" cols="71" rows="5" id="prof_enlargement">
</textarea></p>
<p><input type="submit" name="Submit" value="Add new item" id="add_prof" /></p>
</fieldset>

3 个答案:

答案 0 :(得分:4)

您可以克隆它们。首先用父div包裹那些元素,例如“模板”:

<div id="template">
  <p>Item <input type ="text" size="25" name="prof_item" /><br /></p>
  <p>Duration <input type ="text" size="25" name="prof_duration" /><br /></p>
  <p>Enlargement <label for="enlargement"></label></p>
   <p><textarea name="prof_enlargement" cols="71" rows="5" id=""></textarea></p>
</div>

第二个占位符将包含您添加的所有克隆:

<div id="placeholder">
  <div id="template">
     <p>Item <input type ="text" size="25" name="prof_item" /><br /></p>
     ...
   </div>
</div>

最后这个JS代码将添加元素:

var _counter = 0;
function Add() {
    _counter++;
    var oClone = document.getElementById("template").cloneNode(true);
    oClone.id += (_counter + "");
    document.getElementById("placeholder").appendChild(oClone);
}

只需在按钮点击事件中调用“添加”功能..计数器必须避免为多个元素使用相同的ID。

实时测试案例:http://jsfiddle.net/yahavbr/eW6j4/

答案 1 :(得分:0)

$('#button').click(function() {
    $('#fieldset').clone().insertAfter($('#fieldset'));
});

尝试这样的事情,克隆()很有用 http://api.jquery.com/clone/

- 评论后编辑 - 将其添加到您的htmlpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script>
$(document).ready(function() {
    $('#add_prof').click(function() {
            $('#fieldset').clone().insertAfter($('#fieldset'));
    });
});
</script>

- 在您发表评论后再次进行评估 -

为了让功能也适用于新添加的输入,我们使用'live'。我建议的.click在代码执行时对元素起作用。当我们使用.live时,该函数将与您选择的每个现有元素一起执行,但也会与您选择的未来元素一起执行。使用此:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script>
$(document).ready(function() {
    $('fieldset input').live('click',function() {
            $(this).parent('fieldset').clone().insertAfter($(this).parent('fieldset'));
    });
});
</script>

如果代码有效,请将此答案标记为“已接受的答案”,以便具有相同问题的其他用户可以立即看到工作代码。

答案 2 :(得分:0)

我更喜欢javascript方式

var fieldset= document.getElementById('fieldset');
var fieldParent = fieldset.parentNode;
var newFieldSet = document.createElement('fieldset');
newFieldSet.innerHTML = fieldset.innerHTML;
fieldParent.appendChild(newFieldSet);

问候:)

相关问题