Using JQuery to create dynamic HTML select elements.

This week I'm working a lot with JQuery and when searching for handling html select element I found little information about it, so I decide blog a little about this subject.

Typically you want add and remove options from a select box, so I setup a little page that does an append to a select and removes an option too.

We will have a Fruit Basket, we put a item in our hand and then eat it. Here's the basket (listing 1):

 1 <html>
 2   <head>
 3     <script type="text/javascript" src="jquery.js"></script>
 4   </head>
 5   <body>
 6     <table>
 7        <tr>
 8          <td>
 9            Fruit Basket<br>
10            <select name="basket" size=5 >
11              <option value="apple">Apple</option>
12              <option value="banana">Banana</option>
13              <option value="orange">Orange</option>
14              <option value="grape">Grape</option>
15              <option value="starfruit">Star Fruit</option>
16            </select><br>
17            <input type="button" value="Pickup" name="pickup">
18          </td>
19          <td>
20            Hand<br>
21            <select name="hand" size=5 ></select><br>
22            <input type="button" value="Eat!" name="eat">
23          </td>
24        </tr>
25     </table>
26   </body>
27 </html>

This HTML is a simple one, the table was inserted just to put the selects side-by-side. Note that I didn't put any javascript event handler like onClick(), onChange() and etc. This because with JQuery you can add the event handler very easily without cluttering the HTML.

Now comes the good stuff, insert a <script type="text/javascript"> tag and let's see JQuery's magic (listing 2).

 1 <script type="text/javascript">
 2 $(document).ready(function() {
 3   // the good stuff goes in here...
 5   // when somebody clicks on Pickup...
 6   $("input[name='pickup']").click(function() {
 8     // there's something selected in our basket?
 9     if($("select[name='basket'] :selected").length > 0) {
11       fruit_text   = $("select[name='basket'] :selected").text();
12       fruit_value  = $("select[name='basket'] :selected").attr("value");
14       // put the fruit in hand...
15       $("select[name='hand']").append(new Option(fruit_text, fruit_value));
17       // remove the fruit from the basket...
18       $("select[name='basket'] :selected").remove();
20     } else { return false; } // don't bother with a empty selection
22   });
24   // let's eat!
25   $("input[name='eat']").click(function() {
26       $("select[name='hand'] :selected").remove();
27   });
29 });
30 </script>

Now let's explain what is happening.

If you already knows JQuery you recognize the line 2, this is a simple way to trigger your script when the document is ready, it's a good practice. Insures that your script will not fire before the browser finished rendering all page elements.

In line 6 and 25 we define one anonymous (formally a lambda) function that will be fired on a click event for our both buttons. Pay attention on JQuery selector syntax it's very important! In line 6 we say to JQuery:


and JQuery understand this:

"Give me the input element which has the attribute name equals to pickup."

If we were ambiguous in our selector JQuery will return more than one element, in this case we could iterate over the matches found with each() helper.

We ask to JQuery in line 9 if there's something selected in our basket, if the length of selected fruits is greater than zero let's do something.

We use some accessors from JQuery and save the text and the value of attribute "value" in two variables, lines 11 and 12. After that, in line 15, we tell JQuery to append a new Option object which is basically the same option selected in our basket.

Now the last step in this event is remove the fruit from the basket, one way to do this is calling remove() on the JQuery object.

If you payed attention on the above explanation lines 25 to 27 should be clear. We select what is selected on our hand and just "eat it" (in fact we remove the element). That's it, simple and clean.

Published in Jul 08, 2008