I want to create a dynamic amount of fields determined by the value selected in a dropDownList. As this will be executed client side it must be done through Javascript. I know I could achieve this effect by creating ALL of the fields before hand and then simply using css to show/hide each one, but this is a lot of repetitive code.
Through trial and error I’ve got it to kind of work, but it either deletes my values when changing my dropdownlist or adds too many boxes if I don’t have it delete the previously created boxes before creating new ones.
Is there a simple way to accomplish what I’m trying to do, without losing entered values on change of the dropdownlist? My attempt at making something is below.
function doAThing() {
var attemptsValue = parseInt(document.forms['ProgramApplicationForm'].elements['VerificationPrimaryHomePhoneAttemptsDropDownList'].value);
if (attemptsValue == null) {
document.getElementById('VerificationPrimaryHomePhoneAttemptDate').innerHTML = null;
} else if (document.getElementById('VerificationPrimaryHomePhoneAttemptDate').innerHTML == null) {
for (counter = 1; counter < attemptsValue + 1; counter++) {
document.getElementById('VerificationPrimaryHomePhoneAttemptDate').innerHTML +=
'<label for="VerificationPrimaryHomePhoneAttemptDate' + counter + '">Attempt ' + counter + ' Date:</label><input type="text" name="VerificationPrimaryHomePhoneAttemptDate' + counter + '" value="" id="p-dod-date-picker" maxlength="10" class="size-ten" placeholder="yyyy-mm-dd" title="yyyy-mm-dd" pattern="\d{4}-\d{2}-\d{2}"/>';
}
} else {
document.getElementById('VerificationPrimaryHomePhoneAttemptDate').innerHTML = null;
for (counter = 1; counter < attemptsValue + 1; counter++) {
document.getElementById('VerificationPrimaryHomePhoneAttemptDate').innerHTML +=
'<label for="VerificationPrimaryHomePhoneAttemptDate' + counter + '">Attempt ' + counter + ' Date:</label><input type="text" name="VerificationPrimaryHomePhoneAttemptDate' + counter + '" value="" id="p-dod-date-picker" maxlength="10" class="size-ten" placeholder="yyyy-mm-dd" title="yyyy-mm-dd" pattern="\d{4}-\d{2}-\d{2}"/>';
}
}
}
Use
element.removeChildandelement.appendChildinstead of meddling withinnerHTML. This will enable you to remove specific nodes in the DOM:Demo
If you want you can still use
innerHTMLon the created labels, this will make the first function much smaller. Also note thatnullisn’t a number, it’s an object.