Main page | About | Articles | Previous Posts | Archives

Sunday, October 01, 2006

<select> boxes

I'm sitting in the #Javascript channel in Quakenet at IRC. Pretty often you see someone who wants to something to happen when you choose an item from a select box...

"I want to show some fields if user selects X from my list"

"I want to have 3 <select> boxes and when you choose 1 there will come a new select box.. how can I do that?"


I made a quite simple sample script of this.

I thought it might be a good idea to explain it a bit, though.

Starting with the HTML code:

the basic idea is to have a select element and give it an ID so we can easily use it in JavaScript. In the example, the select elements ID is "selector".

Then we need something to show and hide depending on what's selected: in the example, a couple of div elements. Yet again, we should give these some IDs so they can be easily accessed from JS... in the example they're called "right_1" and "right_2".

These divs are also hidden by default using the CSS definition "display: none".

In the select element, we use the onchange event to call our JavaScript function. As you can see from the HTML code, onChange="ShowRight()"

Now let's look at the JavaScript function...

First, we use document.getElementById() function to find the select element. We use .selectedIndex to find the numeric index of the item which is currently selected... note that the first one is 0, not 1.

We save this index to a variable called "selected".

After this we hide the two divs we have. This is because the user might have selected something from the select already and one of the divs might be visible.

Then we have a switch statement. This is used to do something depending on what the value saved in selected is.

As you can see, if the value is 1 the code uses document.getElementById() to find right_1 and then sets it's CSS value display to "block" and if the value is 2, it shows the right_2 element instead.

Pretty simple stuff, isn't it?

Labels: ,


Post a Comment

<< Home