使用jQuery动态添加HTML表单域 [英] Dynamically adding HTML form field using jQuery
本文介绍了使用jQuery动态添加HTML表单域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
.append()
这里)没有重新加载页面或重写表单? (使用jQuery) 编辑:
这是HTML:
< form id =form-0name =0>
< b>什么是bla?< / b>< br>
< input type =radioname =answerNvalue =0> aaa< br>
< input type =radioname =answerNvalue =1> bbb< br>
< input type =radioname =answerNvalue =2> ccc< br>
< input type =radioname =answerNvalue =3> ddd< br>
//这是我想要动态添加新的收音机或文本行
< input type =submitvalue =提交你的答案>
//但是这里是.append()将它放在哪里!
< / form>
解决方案
这个线程似乎是令人困惑的是:
$('。selector')。append(< input type ='text'/>);
将目标元素追加为.selector的子代码。
和
$(< input type ='text'/>\").appendTo ( '.selector');
将目标元素追加为.selector的子代码。
注意目标元素的位置和
您想要做的是这样的:
$(function(){
//在
$(< input type ='text'value =''/ >)
.attr(id,myfieldid)
.attr(name,myfieldid)
.prependTo(#form-0);
// OR
//在结尾处附加输入控件
$(< input type ='text'value =''/> )
.attr(id,myfieldid)
.attr(name,myfieldid)
.appendTo(#form-0);
// OR
//看到.after()或.before()在api.jquery.com库
});
Since I cant use div inside forms, I wonder how can I add new field in the middle of the form (and I can't use .append()
here) without reloading the page or rewriting the form? (using jQuery)
EDIT: this is the 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>
解决方案
What seems to be confusing this thread is the difference between:
$('.selector').append("<input type='text'/>");
Which appends the target element as a child of the .selector.
And
$("<input type='text' />").appendTo('.selector');
Which appends the target element as a child of the .selector.
Note how the position of the target element & the .selector change when using the different methods.
What you want to do is this:
$(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
});
这篇关于使用jQuery动态添加HTML表单域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文