[jQuery] append() not updating DOM
I have problem with elements that have been added to the DOM via append() not being reliably returned via selectors.
Happens when I perform append between containers thus.
1. Append Container 1
2. Append Container 1
3. Append Contrainer 2
4. Append Contrainer 2
5. Append Container 1
Say you have two containers, thus:
<!--Init Values-->
<div id="initValues">
</div>
<!--Create Values-->
<form id="frmCreate" action="/siteignite/poppage/ajx_crud" method="post">
<input class="hiddentext" id="pendTemplate" name="pendTemplate" type="text">
<input class="hiddentext" id="pendPage" name="pendPage" type="text">
<input class="hiddentext" id="pendCRUD" name="pendCRUD" value="C" type="text">
</form>
And you add a child textarea to each eleemtn based on whether the container already has a child with that id or not using code like this:
$("#updateForm").click(function () {
createfld = "#frmCreate > #"+window.CurrentPanel;
if ($(createfld).length == 0) {
$('#frmCreate').append("<textarea class='hiddentextdebug' cols=40 rows=10 postvals='y' id='"+window.CurrentPanel+"' name='"+window.CurrentPanel+"'></textarea>");
$(createfld).val(html);
};
});
$("#updateInit").click(function () {
initfld = "#initValues > #"+window.CurrentPanel;
if ( $(initfld).length == 0 ) {
$("#initValues").append("<textarea class='hiddentextdebug' cols=40 rows=10 initvals='y' id='"+CurrentPanel+"'>unset</textarea>");
}
});
If the container has an element with that id, it does not append(), otherwise, it does.
You can watch the length value as you follow this sequence of steps:
1. Append Container 1 -- length: 0
2. Append Container 1 -- length: 1
3. Append Contrainer 2 -- length: 0
4. Append Contrainer 2 -- length: 1
5. Append Container 1 -- length: 0
And resulting generated HTML (as copied from FF):
<!--Init Values-->
<div id="initValues">
<textarea class="hiddentextdebug" cols="40" rows="10" initvals="y" id="para1">unset</textarea>
<textarea class="hiddentextdebug" cols="40" rows="10" initvals="y" id="para2">unset</textarea>
<textarea class="hiddentextdebug" cols="40" rows="10" initvals="y" id="para1">unset</textarea>
</div>
<!--Create Values-->
<form id="frmCreate" action="/siteignite/poppage/ajx_crud" method="post">
<input class="hiddentext" id="pendTemplate" name="pendTemplate" type="text">
<input class="hiddentext" id="pendPage" name="pendPage" type="text">
<input class="hiddentext" id="pendCRUD" name="pendCRUD" value="C" type="text">
<textarea class="hiddentextdebug" cols="40" rows="10" postvals="y" id="para1" name="para1"></textarea>
<textarea class="hiddentextdebug" cols="40" rows="10" postvals="y" id="para1" name="para1"></textarea>
</form>
Clearly, it should not be possible to add multiple child elements to a container with the same id "para1" since the second attempt should ahve returned a length of "1".