使用jQuery动态添加HTML表单字段

ily*_*lyo 33 html jquery dom

由于我不能在表单内部使用div,我想知道如何.append()在不重新加载页面或重写表单的情况下在表单中间添加新字段(我不能在这里使用)?(使用jQuery)

编辑:这是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>
Run Code Online (Sandbox Code Playgroud)

小智 65

这个线程似乎令人困惑的是:

$('.selector').append("<input type='text'/>"); 
Run Code Online (Sandbox Code Playgroud)

将target元素追加为.selector的子元素.

$("<input type='text' />").appendTo('.selector');
Run Code Online (Sandbox Code Playgroud)

将target元素追加为.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

});
Run Code Online (Sandbox Code Playgroud)


Fre*_*rik 13

这将在输入字段后面输入一个id为"password"的新元素.

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

不确定这是否回答了你的问题.


Rob*_*Rob 8

您可以使用appendappendTo(等等)方法添加任何类型的HTML :

jQuery操作方法

例:

$('form#someform').append('<input type="text" name="something" id="something" />');
Run Code Online (Sandbox Code Playgroud)


pix*_*bby 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>
Run Code Online (Sandbox Code Playgroud)