Reputation: 1876
I have a form in which I ask the user how many file inputs they need, and I'd like to generate the suitable number of file browsing inputs dynamically based on the answer.
Here is my attempt:
$("#howmany").change(function()
{
var htmlString = "";
var len = $(this).val();
for (var i = 0; i <= len; i++)
{
htmlString += "
<tr>
<td>
<input name="ufile[]" type="file" id="ufile[]" size="50" />
</td>
</tr>
";
}
$("#dynamic_upload").html(htmlString);
}
HTML
<input id="howmany" />
<table id="dynamic_upload">
</table>
The idea being that repeating "units" of inputs will be generated based on the number entered.
But it isn't working, any idea where I'm going wrong?
EDIT: More clarity on "it isn't working" (apologies). When I include this code, after entering the number into the field "howmany" there is no visable reaction. No error messages appear, although - is there an error log somewhere I don't know how to read? (new to this)
Upvotes: 0
Views: 718
Reputation: 64526
It's not possible to create a string like that. Try:
htmlString += "<tr>";
htmlString += "<td>";
htmlString += '<input name="ufile[]" type="file" id="ufile[]" size="50" />';
htmlString += "</td>";
htmlString += "</tr>";
Also remember you need to use single quotes around the string if it contains double quotes, or escape them.
You are also missing );
from the end of the function:
$("#dynamic_upload").html(htmlString);
} <--- this should be });
Upvotes: 2
Reputation: 191729
You can't have newlines in JavaScript strings. Moreover, you are using double-quotes within the string (i.e. for the <input>
attributes). Possible rewrite:
htmlString += '<tr><td><input name="ufile[]" type="file" id="ufile[]" size="50"></td></tr>';
In the future, please give a more descriptive problem than "it isn't working" -- for example, do you get any error messages?
Upvotes: 1