如何动态创建表单元素 [英] How to dynamically create a form element
问题描述
我有以下代码
我正在尝试动态创建带有和不带标签的单选按钮。当我创建单选按钮时,我无法将文本放在单选按钮中,这里是没有标签的代码
这就是期望
I have the following code I am trying to dynamically create radio button with and without labels in them. I am unable to put the text in radio button when I create radio button, here is the code without labels This is what expect
<input type="radio" name="Alex" value="Alex"/>Alex
$('<input>').attr({
type:'radio',
name:'name',
value: "Alex",
text:"Alex"
}).insertAfter("#divid"));
现在有标签,
<label><input type="radio" name="Alex" value="Alex"/>Alex<label>
//create a label tag
var label = $('<label>', { text:"Alex"});
//append input tag to label
$(label).append($('<input>').attr({
type:'radio',
name:"Alex",
value:"Alex"
}).insertAfter("#divid"));
以上两者都不会在控制台上产生任何错误,但它不会生成正确的HTML标记我我有兴趣。还有一种方法可以直接在无线电中添加标签,因为我动态创建它们。我的意思是我不想创建一个标签标签,并附加单选按钮。非常感谢您的帮助
Both of the above does not produce any error on console but it does not produce the right HTML tag I am interested in. Also is there a way to directly add label to radio as I create them dynamically. I mean I dont want to create a label tag separetely and append to it the radio button. Many Thanks for your help
推荐答案
动态创建标签
和收音机
var $input = $('<input />', {
type : "radio",
name : "name",
value : "alex"
});
$("<label />", {
insertAfter: "#somediv", // (or use appendTo: to insert into it)
append: [$input, "Alex"] // include our $input and also some text description
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="somediv">DIV</div>
这篇关于如何动态创建表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!