2011-05-23 61 views
31

由于我不能在表单中使用div,我不知道如何在表单中间添加新字段(并且我无法在此处使用.append())而无需重新加载页面或重写表单? (使用jQuery)使用jQuery动态添加HTML表单字段

编辑: 这是HTML:

<form id="form-0" name="0"> 
<b>what is bla?</b><br> 
<input type="radio" name="answerN" value="0"> aaa <br> 
<input type="radio" name="answerN" value="1"> bbb <br> 
<input type="radio" name="answerN" value="2"> ccc <br> 
<input type="radio" name="answerN" value="3"> ddd <br> 
//This is where I want to dynamically add the new radio or text line 

<input type="submit" value="Submit your answer"> 
//but HERE is where .append() will put it! 

</form> 
+2

您的问题没有什么太大的意义。你已经尝试了什么? – 2011-05-23 15:25:10

+0

我试图slelect形式的一个前方的最后一个孩子,并使用追加到它,但它没有工作 – ilyo 2011-05-23 15:38:27

+1

是什么让你觉得你不能使用内部'form'元素'div'元素? – zzzzBov 2011-10-20 17:04:22

回答

61

什么似乎混淆这个线程之间的区别在于:

$('.selector').append("<input type='text'/>"); 

其中追加目标元素作为.selector的孩子。

而且

$("<input type='text' />").appendTo('.selector'); 

其中追加目标元素作为.selector的孩子。

注意如何使用不同的方法当目标元件的位置&的.selector变化。

你想要做的是什么:

$(function() { 

    // append input control at start of form 
    $("<input type='text' value='' />") 
    .attr("id", "myfieldid") 
    .attr("name", "myfieldid") 
    .prependTo("#form-0"); 

    // OR 

    // append input control at end of form 
    $("<input type='text' value='' />") 
    .attr("id", "myfieldid") 
    .attr("name", "myfieldid") 
    .appendTo("#form-0"); 

    // OR 

    // see .after() or .before() in the api.jquery.com library 

}); 
8

你可以像appendappendTo方法添加任何类型的HTML(其中包括):

jQuery manipulation methods

例如:

$('form#someform').append('<input type="text" name="something" id="something" />'); 
6

像这样可能的工作:

<script type="text/javascript"> 
$(document).ready(function(){ 
    var $input = $("<input name='myField' type='text'>"); 
    $('#section2').append($input); 
}); 
</script> 

<form> 
    <div id="section1"><!-- some controls--></div> 
    <div id="section2"><!-- for dynamic controls--></div> 
</form> 
+0

@Rob,@pixelbobby,tahnx但事情是,如果有一个完整的形式,我不能使用追加,因为它会插入标签下面的一行所以它不会是形式的一部分,我怎么可以将$输入表格的中间? – ilyo 2011-05-23 15:31:32

+0

@IlyaD - 追加插入新元素插入标签,在这种情况下,将会把新的输入表单标签内。 – 2011-05-23 15:38:07

+1

@llyaD,看我更新的答案。我添加了将控件插入表单内特定位置的代码。此外,可以使用'prepend()','insertAfter()'和'insertBefore()'将控件放置在元素中的特定位置。 – pixelbobby 2011-05-23 16:35:54

13

这将ID为“密码”输入字段后插入一个新的元素。

$(document).ready(function(){ 
    var newInput = $("<input name='new_field' type='text'>"); 
    $('input#password').after(newInput); 
}); 

不知道这是否回答你的问题。

0

似乎有使用appendTo框架集ID追加到在Chrome浏览器形式的错误。 用div直接跳出属性类型,它工作。

相关问题