Unable To Reference To Dynamically Created Element By Name
Solution 1:
Got it!!
The problem is that when a Jquery's plugin datepicker
is applied to an element, a class is set to the input called hasDatepicker
.
When you call the plugin again, it checks first if the class already exists... If it does, than Jquery doesn't apply the datepicker, because it understands that it is already applied.
Since you are copying the innerHTML
from the pre-existing cell:
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
you're copiyng the input with the class hasDatepicker
already set on it. So Jquery won't implement the plugin.
A simple fix is to remove the class before the datepicker
call:
var setClass = function() {
$('[name="when"]').removeClass("hasDatepicker").datepicker();
}
Solution 2:
You should just initialize the plugin on the newly-added elements. You need to take some special actions, though.
The datepicker plugin puts a class hasDatepicker
on elements that it has already initialized, and doesn't re-initialize them. Since you're copying an element that has this class, you need to remove it so that it will be re-initialized. Second, if the element doesn't have an ID, datepicker adds a randomish ID to it. IDs need to be unique, but your code is copying the ID. In my code below, I simply remove the ID from the elements, so the plugin will add a new, unique one. If I didn't do this, the datepicker on a new row would fill in the first row (because it uses the ID internally when finding the input to update after you select something from the datepicker).
functionaddRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[01].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case"text":
newcell.childNodes[0].value = "";
break;
case"checkbox":
newcell.childNodes[0].checked = false;
break;
case"select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
setClass(row);
}
functionsetClass(newrow) {
$(newrow).find('.hasDatepicker').removeAttr('id').removeClass('hasDatepicker').datepicker();
}
Post a Comment for "Unable To Reference To Dynamically Created Element By Name"