2011-05-23 38 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直接跳出屬性類型,它工作。