Last active
September 20, 2015 23:05
-
-
Save k4kfh/8a4320f29412049422cf to your computer and use it in GitHub Desktop.
buildDropdown.js is a simple JavaScript program that can build an HTML <select> dropdown from a JavaScript array variable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//BUILDDROPDOWN.JS | |
//by Hampton [evilgeniustech.com] | |
//buildDropdown.js is a useful script that makes it easy to build an HTML dropdown <select> tag from a JavaScript array. | |
//How to use: | |
//The function accepts 2-3 parameters. | |
// - id >>> this is the HTML ID of the select element you wish to modify, as a string of course. | |
// - list >>> this is the JavaScript array you want to use with the dropdown. | |
// - clear >>> this is a boolean which decides whether or not the script removes existing dropdown choices. For example, if I called this with clear = true, it would delete any existing <option> tags and start fresh. If it is false or undefined, it simply appends the new <option> tags to the existing ones, if any. | |
//Basically, you must specify an ID and a JS array. If you specify true or false for clear, you get what you specify, but if you don't specify we assume false. | |
//Example: buildDropdown("myDropdownID", ["test 1", "option I made up", "dude this rocks"], true) | |
//This example would add the options "test 1", "option I made up", and "dude this rocks" to the <select> element with the ID "myDropdownID", and it would get rid of any existing option elements. | |
//Here's the actual code, have fun! You can just put this in your <head> and you're good to go. No libraries needed or anything fancy. Easy, right? | |
function buildDropdown(id, myList, clearOrNot) { | |
var sel = document.getElementById(id); | |
if (clearOrNot == true) { | |
sel.innerHTML = undefined | |
} | |
var newFragment = document.createDocumentFragment(); | |
myList.forEach(function(list, index) { | |
var opt = document.createElement('option'); | |
opt.innerHTML = list; | |
opt.value = list; | |
newFragment.appendChild(opt); | |
}); | |
sel.appendChild(newFragment); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment