Dynamically updating html

Changing a select element's content on the fly is a powerful feature of Java Script that's just as practical.

It forms the basis of implementing inter-dependant select menus, where the selection of one menu changes the contents of another.

In this tutorial, lets look at how this is done, and also, how to create a 2 level interdependent select list using the technique. The basic technique for changing a select element's content using Java Script is a two part process.

I'll use the following SELECT element as an example: Doing the above instantly empties the select element, ready to be populated with new data.

2) Repopulate the select menu with new options (aka content), using the Option() constructor on each option: document.myform.master.options[0]=new Option("Sports", "sportsvalue", true, false) document.myform.master.options[1]=new Option("Music", "musicvalue", false, false) document.myform.master.options[2]=new Option("Movies", "moviesvalue", false, false) The select menu is now repopulated with 3 new entries ("Sports", "Music", and "Movies").

In case you're wondering, the Option() constructor supports the following four parameters, the later two optional: For more info, see Option() constructor in our Java Script Reference.

When repopulating a select element's content, you may want to use a loop instead of changing each option one by one.

This lets you add new options to the end of the select element without knowing any info about its existing length.

Moving on, you can also selectively remove a single option without performing mass destruction on all options within select first.

This is done by setting the desired option to null.

Doing so removes the option from the list, with the options below it moving up to occupy the void: You can also easily remove multiple options from select, provided they are at the end of the list.

Note The feedback system for this content will be changing soon. If content within a comment thread is important to you, please save a copy.

For more information on the upcoming change, we invite you to read our blog post.

Please or register to post comments
If spammers comment on your content, only you can see and manage such comments Delete all

Dynamically updating html introduction

Dynamically updating html

Recent posts