Dynamically Populating A Listbox From A Textbox Via JavaScript / DOM

Recently asked on Yahoo! Answers:

Where can I find the javascript that lets me move an item from a textbox to a list?

I have a text field, an ADD button, a list feld (empty) and a DELETE button. I want the user to be able to type something into the textfield, click ADD, and have that item appear in the list. If they select an item from the list and click DELETE, then the item would be deleted. Can someone post the code or a link to some free javascript?

You can actually find bits and pieces of this code out on the Interweb (as one of my clients calls it) quite easily, but packaged together isn’t so easy. So, I’ll tie it all together and explain how it works.

As always, we start with a simple form, and again, I’m cheating on layout with a table. Note that we assign onclick events to our buttons that will be the names of our JavaScript functions:

<form id="form1" action="" method="post" name="form1">
<table>
<tbody>
<tr>
<td><label>Enter Item: <input id="mytextbox" type="text" name="mytext" /> <input id="myadd" onclick="addListItem()" type="button" name="myadd" value="Add Item" /> </label></td>
<td><select id="mylistbox" multiple="multiple" name="mylist" size="10"></select></td>
<td><input id="mydelete" onclick="removeListItem();" type="button" name="mydelete" value="Remove Selected Items" /></td>
</tr>
</tbody>
</table>
</form>

We begin the JavaScript with a function that doesn’t seem related at all: A basic string-trimming function. What this function does is trim all leading and trailing white space from a line. We use this function because we don’t want to handle bad text input from the user, and that includes simply entering nothing more than white space into the textbox.

Our function merely starts at the beginning of the input string and looks for whitespace characters, removing them if they are found. Then, it finds the end of the string and starts knocking white space characters off the end, one by one.

function trimString(input) {
	var output = input;
	while (output.substring(0, 1) == ' ') {
		output = output.substring(1, output.length);
	}
	while (output.substring(output.length - 1, output.length) == ' ') {
		output = output.substring(0, output.length - 1);
	}
	return output;
}

We can now begin the project in earnest. First up, the function that will add items to our listbox. We assign two variables the textbox and listbox elements from our page; we declare a Boolean that will help us figure out if the textbox contains a value that’s already in our list; and we declare an Option variable that will allow us to add items to the listbox.

function addListItem() {
	var textbox = document.getElementById('mytextbox');
	var listbox = document.getElementById('mylistbox');
	var inList = false;
	var myText = trimString(textbox.value);
	var myOption;

Notice that we trimmed the myText variable before we began; we want to make sure there is something worth processing. Additionally, we want to make sure that we don’t add list items based on leading or trailing spaces. For example, to humans, “Hello World!” is the same as “Hello World! “, but to a computer, that trailing space makes the two strings different.

The code below takes that trimmed text and compares it to all the options currently in the listbox. If the item is already in the options, the value of the text box will not be added.

We need to consider case, as well. In the code block below, I cast both the value of the textbox and the values in the listbox to lower case as I compare them, because I don’t want options in the listbox that repeat an item based on case.

For example, if I don’t cast my comparisons to lower case, then “Banana”, “banana”, “bAnana” and “BaNana” would all be added to the list box as options. If that’s what you actually want to have happen, just remove the toLowerCase() methods from the code block below.

To add an option to a listbox, we just create an option with the text and value we want, then append it to the end of the options list.

if(myText != '') {
	for(var i = 0; i &lt; listbox.options.length; i++) {
		if(myText.toLowerCase() == listbox.options[i].text.toLowerCase()) {
			inList = true;
			break;
		}
	}

	if(!inList) {
		myOption = new Option(myText, myText);
		listbox.options[listbox.options.length] = myOption;
	}
}
You could have this list automatically sort itself alphabetically. To do that, you’d declare a global array and store your options in that array; every time you added an option, you’d add the item to that global array, then sort it.

In turn, you’d remove all options from the listbox as it is now, then rebind all the items in the global array to your listbox as options.

To remove an item, we simply see if it is checked in the listbox; if it is, we set it to null.

function removeListItem() {
	var listbox = document.getElementById('mylistbox');

	for(var i = 0; i &lt; listbox.options.length; i++) {
		if(listbox.options[i].selected) {
			listbox.options[i] = null;
		}
	}
}

Here’s a working demo:

http://demo.dougv.com/js_dynamic_listbox/

You can simply save the page as is to work with it.

3 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Check out the Commenting Guidelines before commenting, please!
  • Want to share code? Please put it into a GitHub Gist, CodePen or pastebin and link to that in your comment.
  • Just have a line or two of markup? Wrap them in an appropriate SyntaxHighlighter Evolved shortcode for your programming language, please!