I am having trouble with generating text fields dynamically. I have a select box in the form and what I want to do is to create text fields on the basis of selection of number in drop down list. So if the user selects one I want to create one text field below it. I am using javascript and onChange event to accomplish it. But the code is not working in any of the browsers.
Here is The javascript function I am using in the head section of the document:
function addField()
{
alert("Hello");
var num=document.forms["myForm"]["timePerDay"].value;
for(var i=0;i<num;i++)
{
var element = document.createElement("input");
element.setAttribute("type", input);
element.setAttribute("name", time[] );
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
}
And Select field is:
<select name="timePerDay" onChange="javascript:addField();">
<option selected="selected">Select One</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<span id="fooBar">
</span>
It seems like onChange is not firing at all in any browser as I tried to put alert message in the JS function and even it is not working. So can you please tell me what is the problem.
You can see the page at : http://motushealth.com/form1.html
PS:
I am using another JS function on the form to validate it and it works on Onsubmit . It is working perfectly.
The problem is a syntax error here:
element.setAttribute("name", time[] );time[]is valid in php, but not in js.EDIT:
The alternate approach is to not use inline js (
...onClick='javascript:addField();'...). Instead do the following onwindow.onloador better, on theonDomReadyevent.JS:
And markup can be: