One of the most common things we want to do when web programming is supply a list of values in drop-down or form fields etc.. So we don’t have to maintain the values ( sometimes very large lists ) in the code itself it is often times best practice to keep the in your db tables. Here are some code snippets that will help with that.
// Scott Andrew Alpaugh code samples here is some javascript that will populate a dropdown or form field from a database table
// for demo purposes we will assume there is a select element with id=”dropdown” in the HTML
// assume there is a function called getData that returns an array of objects from the database table
// each object has a property called name that will be used as the option text
// use a for loop to iterate over the array and create option elements
// append the option elements to the select element
var dropdown = document.getElementById(“dropdown”); // get the select element
var data = getData(); // get the data from the database table
for (var i = 0; i < data.length; i++) { // loop over the data array
var option = document.createElement("option"); // create a new option element
option.value = data[i].name; // set the value attribute to the name property
option.text = data[i].name; // set the text content to the name property
dropdown.appendChild(option); // append the option to the select element
}
Thanks for checking out the blog today ..sorry it's been a while since I posted. I've been working on building an audience for my new YouTube channel @time4ten