Reputation: 9208
I am generating dynamically some selects in a jsp page with javascript. The code works fine. But I having an issue, and don't know how to deal with it. Well, this is the javascript code:
$('#addRow').click(function(){
i++;
//stuff categories
var categoriesStr = '${stuffCategoriesListStr}';
categoriesStr = categoriesStr.replace('[', '');
categoriesStr = categoriesStr.replace(']', '');
var categoriesList = categoriesStr.split(', ');
var selectCategoriesHtml = "<select id='category"+i+"' style='width: 200px;' onchange=\"retrieveUrlAjax('ajaxstuff.action?category='+this.value, 'menusCombobox"+i+"')\"><option value='-1'>-- Select category --</option>";
for (j = 0; j < categoriesList.length; j++) {
var option = "<option value='"+categoriesList[j]+"'>"+categoriesList[j]+"</option>";
selectCategoriesHtml += option;
}
selectCategoriesHtml += "</select>";
//end os stuff categories
//units list
var unitsStr = '${unitsListStr}';
unitsStr = unitsStr.replace('[','');
unitsStr = unitsStr.replace(']','');
var unitsList = unitsStr.split(', ');
var selectUnitsHtml = "<select id='unit+"+i+"' style='width: 200px;'><option value='-1'>-- Select unit --</option>";
for (j = 0; j < unitsList.length; j++) {
var option = "<option value='"+unitsList[j]+"'>"+unitsList[j]+"</option>";
selectUnitsHtml += option;
}
selectUnitsHtml += "</select>";
//end of units list
var d = document.getElementById("fields");
d.innerHTML += "<table width='100px'>\n\
<tr>\n\
<td>"+selectCategoriesHtml+"</td>\n\
<td width='100px;'><div class='menusCombobox"+i+"'><select style='width: 200px;'/></div></td>\n\
<td width='1%'><input type='text' style='width: 40px;' id='"+i+"' value='1'/></td>\n\
<td width='200px'>"+selectUnitsHtml+"</td>\n\
</tr>\n\
</table>";
});
And here it is the div:
<div id="fields"></div>
And the result:
1 screen: http://img199.imageshack.us/img199/4662/screenshot1hrpl.png
2 screen: http://img827.imageshack.us/img827/5717/screenshot2hn.png
The problem is that when I am choosing something in first row, and then add another row, then all the data from the first row that was chosen is reseted. You can see this in the first and second screens. I think the problem is in the innerHTML, but I haven't found other alternatives. Maybe you guys can help me.
Upvotes: 0
Views: 124
Reputation: 24236
I think it is the innerHTML
that's causing you the problem, have a look at this question -
Is it possible to append to innerHTML without destroying descendants' event listeners?
As you're using jQuery could you use something like append or after instead?
Upvotes: 2