I have created dynamic elements using javascript. These elements are created when i input an int value based on the value i get the number of elements.
My problem is that if i change the int value more elements are added instead i just want to keep the number of elements which has been entered in the int field.
Please help
Javascript i use
<script type="text/javascript">
var inival = 0; // Initialise starting element number
// Call this function to add textbox
function addTextBox() {
for (var i = 1; i <= document.getElementById('unit').value; i++) {
if(document.getElementById("my"+i+"Div") != null){
var child = document.getElementById("my"+i+"Div");
alert(child);
var parent = document.getElementById("area");
alert(parent);
alert(i);
parent.removeChild(child);
}
var newArea = add_New_Element();
var htcontents = "Unit"+i+": <input type='text' name='synchunit"+i+"' id='unit"+i+"'/>";
document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
}
}
function add_New_Element() {
inival = inival + 1; // Increment element number by 1
var ni = document.getElementById('area');
var newdiv = document.createElement('div'); // Create dynamic element
var divIdName = 'my' + inival + 'Div';
newdiv.setAttribute('id', divIdName);
ni.appendChild(newdiv);
return divIdName;
}
function removeElement(id){
var child = document.getElementById(id);
alert(child);
var parent = document.getElementById('area');
parent.removeChild(child);
return true;
}
</script>
The way i call it
<tr class="trlist1">
<td style="border:0;">
<input name="projectunit" id="unit" onblur="addTextBox();"/>
</td>
</tr>
<tr>
<td style="border:0;" align="center">
<div id='area'>
</div>
</td>
</tr>
I have solved it myself
just added
function addTextBox() {
document.getElementById("area").innerHTML = '';
for (var i = 1; i <= document.getElementById('unit').value; i++) {
var newArea = add_New_Element();
var htcontents = "Unit"+i+": <input type='text' name='synchunit"+i+"' id='unit"+i+"'/>";
document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
}
}
document.getElementById("area").innerHTML = '';
this line just resets the div.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.