Javascript:动态添加字段

时间:2013-02-19 05:57:10

标签: javascript

我有一个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>

这对我来说非常好。单击按钮时,它会添加文本字段。 但是,我还有另一个选择标记,需要在单击按钮时动态添加。选择表格如下:

<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>

我们如何在输入标记旁添加此选择标记。我是rails开发人员的红宝石,发现很难实现它。

2 个答案:

答案 0 :(得分:2)

希望这会有所帮助:

<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>

答案 1 :(得分:1)

好的,假设您已经拥有JQuery

$("#text").append("<input type='text' name='clients_form[clients_name]' size='32' maxlength='32' value='' id='clients_form_clients_name' />");

同样适用于select和可读代码。你可以把它放在变量

var mySelect ="";
mySelect += '<select id="client_category_name" name="client_category[name]">';
mySelect += '<option value="">Select Category</option>';

等...

$("#text").append(mySelect);