I have a webpage in which I have a div that I would like to repopulate.
For now the content of that div is generated with Javascript the following way:
function foo(array){
for(i=1;i<=maxIndex;i+=1){
document.write ("<label><input type='checkbox'/>" + array[i] + "\n </label><br />")
}
}
and I populate the div the following way:
<div class="bla">
blablabla
</div>
<div class="myDiv" id="myDiv">
<form name="myForm">
<script type="text/javascript">
foo(myArray);
</script>
</form>
</div>
<div class="blah">
blahblahblah
<form>
<select onchange="updateDiv(myArray)">
<option value="1"> Test1 </option>
<option value="2"> Test2 </option>
<option value="3"> Test3 </option>
</select>
</form>
</div>
The reason that I would like to repopulate the div is because I would like
it to be possible for the user to choose the arrangement of the content of the div
(i.e. when the user selects a certain item from a combobox, ‘myArray’
is re-sorted and then myDiv is repopulated such that the content now appears in a different order).
function updateDiv(array){
array.sort();
document.getElementById('myDiv').innerHTML = '<form name="myForm"><script type="text/javascript"> foo(myArray); </script></form>';
}
The problem that I am encountering is that I cannot manage to target the new
content in myDiv when the user selects the combobox.
I have tried using innerhtml, but the new content, which is outputted correctly, shows up in a completely new page instead of showing up in myDiv because of the JavaScript.
EDIT: It seems that now the problem is that innerhtml updates the code in the correct div (at least when I inspect it with firebug) but no text shows up (the JavaScript hasn’t been run…?).
I looked around online and did not seem to find an appropriate solution.
It would be greatly appreciated if someone could point me in the right direction or let me
know if I am approaching this completely wrong.
Thank you
Ok I finally figure out where the problem was: I should not have used so many document.write(), which outputs on a new page.
Instead I store everything in a string and then use document.write() only in the last step, the following way: