[英]Javascript: Adding fields dynamically
I have a html page which looks like this: 我有一个看起来像这样的html页面:
<html>
<head>
<title></title>
<script language="javascript">
fields = 0;
function addInput() {
if ( fields != 3) {
document.getElementById('text').innerHTML += "<input type='text' name='clients_form[clients_name]' size='32' maxlength='32' value='' id='clients_form_clients_name' />";
fields += 1;'
} else {
document.getElementById('text').innerHTML += "<br />More then 3 not allowed.";
document.form.add.disabled = true;
}
}
</script>
</head>
<body>
<form name="form">
<input type="button" onclick="addInput()" name="add" value="Add More" />
</form>
<div id="text">
</div>
</body>
</html>
This works perfectly fine for me. 这对我来说很好用。 It adds text fields when the button is clicked. 单击按钮时,它将添加文本字段。 But, I have another select tag which needs to be added dynamically when the button is clicked as well. 但是,我还有另一个select标签,当单击按钮时也需要动态添加它。 The select form is as below: 选择形式如下:
<select id="client_category_name" name="client_category[name]">
<option value="">Select Category</option>
<option value="1">internal</option>
<option value="2">external</option>
<option value="3">others</option>
</select>
How do we add this select tag alongside the input tag. 我们如何在输入标签旁边添加此选择标签。 I am a ruby on rails developer and finding it hard to implement it. 我是Rails开发人员的红宝石,发现很难实现它。
Hope this helps: 希望这可以帮助:
<html>
<head>
<title></title>
<script >
fields = 0;
function addInput() {
if (fields != 3) {
document.getElementById('text').innerHTML += "<input type='text' name='clients_form[clients_name]' size='32' maxlength='32' value='' id='clients_form_clients_name_"+fields+"' />"+
'<select id="client_category_name_'+fields+'" name="client_category[]"><option value="">Select Category</option><option value="1">internal</option><option value="2">external</option><option value="3">others</option></select>';
fields = fields+ 1;
} else {
document.getElementById('text').innerHTML += "<br />More then 3 not allowed.";
document.form.add.disabled=true;
}
}
</script>
</head>
<body>
<form name="form">
<input type="button" onclick="addInput();" name="add" value="Add More" />
</form>
<div id="text">
</div>
</body>
</html>
Ok assuming you already have JQuery library 好的,假设您已经拥有JQuery库
$("#text").append("<input type='text' name='clients_form[clients_name]' size='32' maxlength='32' value='' id='clients_form_clients_name' />");
same goes on the select
and for readable code. select
和可读代码也是如此。 you can put it first on a variable 您可以先将其放在变量上
var mySelect ="";
mySelect += '<select id="client_category_name" name="client_category[name]">';
mySelect += '<option value="">Select Category</option>';
etc.... 等等....
$("#text").append(mySelect);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.