Reputation: 430
I have a html page which looks like this:
<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. 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.
Upvotes: 0
Views: 4401
Reputation: 429
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>
Upvotes: 3
Reputation: 1573
Ok assuming you already have JQuery library
$("#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. 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);
Upvotes: 1