Create or Remove HTML controls dynamically using javascript

Download Source code: live.com = create-remove-control.zip

Create file input control using javascript
function addFileUploadBox() {
if (!document.getElementById || !document.createElement)
return false;

var uploadArea = document.getElementById(“upload-area”);

if (!uploadArea)
return;

var newUploadBox = document.createElement(“input”);

// Set up the new input for file uploads
newUploadBox.type = “file”;
newUploadBox.size = “70”;

// The new box needs a name and an ID
if (!addFileUploadBox.lastAssignedId)
addFileUploadBox.lastAssignedId = 100;

newUploadBox.setAttribute(“id”, “dynamic” + addFileUploadBox.lastAssignedId);
newUploadBox.setAttribute(“name”, “dynamic:” + addFileUploadBox.lastAssignedId);
newUploadBox.setAttribute(“onchange”, “CheckFileAlongWithDropdown(this)”);
uploadArea.appendChild(newUploadBox);

var newLine = document.createElement(“br”);
newLine.setAttribute(“id”, “br” + addFileUploadBox.lastAssignedId);
uploadArea.appendChild(newLine);

var hdn1 = document.getElementById(‘hdn1’);
hdn1.value = addFileUploadBox.lastAssignedId;
addFileUploadBox.lastAssignedId++;
}

Create “Select” or “Dropdown” control dynamically using javascript
var id = 100;
function AddDropDown() {

if (!document.getElementById || !document.createElement)
return false;

var uploadArea = document.getElementById(“upload-area”);

if (!uploadArea)
return;

//create delete button element
var newBtn = document.createElement(“input”);
newBtn.type = “button”;
if (!AddDropDown.lastAssignedId)
AddDropDown.lastAssignedId = 100;

newBtn.setAttribute(“id”, “btn” + AddDropDown.lastAssignedId);
newBtn.setAttribute(“name”, “btn:” + AddDropDown.lastAssignedId);
newBtn.setAttribute(“value”, “Remove”);
newBtn.setAttribute(“onclick”, “DeleteElement(this)”);
uploadArea.appendChild(newBtn);
//end delete button element creation

$(document).ready(function() {
var data = { ‘ContentPage’: ‘Content Page’, ‘ContentPagewithTitlePage’: ‘Content Page with Title Page’, ‘TitlePage’: ‘Title Page (One Page Only)’,
‘Movie’: ‘Movie’
};
var s = $(”);
s[0].id = “ddl” + id;
s[0].name = “ddl:” + id;

id++;
for (var val in data) {
$(”, { value: val, text: data[val] }).appendTo(s);
}

s.appendTo(uploadArea);
AddDropDown.lastAssignedId++;
});
}

Remove added element from page
function DeleteElement(ctrl) {
var uploadArea = document.getElementById(“upload-area”);
var findDdlId = ctrl.name.split(“:”);
var ddl = document.getElementById(‘ddl’ + findDdlId[findDdlId.length – 1]);
var upload = document.getElementById(‘dynamic’ + findDdlId[findDdlId.length – 1]);
var br1 = document.getElementById(‘br’ + findDdlId[findDdlId.length – 1]);
uploadArea.removeChild(upload);
uploadArea.removeChild(ddl);
uploadArea.removeChild(ctrl);
uploadArea.removeChild(br1);
return false;
}

Share