Below are the steps for adding an option to the dropdown box using JavaScript.
· Create a Option element using JavaScript
var opt = document.createElement("option");
var opt = document.createElement("option");
· Add Option object to dropdown box
document.getElementById("test").options.add(opt);
document.getElementById("test").options.add(opt);
· Assign value and text to the Option object just added
opt.text = "New";
opt.value = "0";
opt.text = "New";
opt.value = "0";
· Insert this Option object just created at top position inside dropdown. This step is optional, if
this step is not performed the Option object will added to dropdown as the last item.
this step is not performed the Option object will added to dropdown as the last item.
document.getElementById("test").insertBefore(opt, document.getElementById("test").firstChild);
· To make the Option object as default when the page loads put this code at the end and include it inside the function and call that function on page load.
document.getElementById("test").options[0].selected=true;
Complete Code:
function addItem()
{
var opt = document.createElement("option");
document.getElementById("test").options.add(opt);
opt.text = "New";
opt.value = "0";
document.getElementById("test").insertBefore(opt, document.getElementById("test").firstChild);
document.getElementById("test").options[0].selected=true;
}
function addItem()
{
var opt = document.createElement("option");
document.getElementById("test").options.add(opt);
opt.text = "New";
opt.value = "0";
document.getElementById("test").insertBefore(opt, document.getElementById("test").firstChild);
document.getElementById("test").options[0].selected=true;
}
Comments
Post a Comment