Here is a very simple jQuery trick to display a message depending on which option is currently selected on a select box. This is very useful especially when there is a need for an explanation or give additional information on some items within a select box.
Here is a demo of this tutorial at work:
Quite handy isn’t it? Here is how to do it in a few simple steps:
First of all, we need to have our select box. Here is how the select box above looks like in code view
<select id="item_select" name="item">
<option>Select an Item</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
For our demo, we will give the select box an id called “item_select” (#item_select) so we can access it later on via jQuery.The values for each option is going to be important as we move on.
The next step will now be creating an array of messages that will correspond to the values of each option. The easiest way to do this is by using the values of each option as the array’s index. Here is how to do it. Place this within the <script> tags:
var message = new Array();
message[1] = "You have selected first item";
message[2] = "You have selected the second item";
message[3] = "You have selected the last item";
Now, the only thing missing is the container in which message will appear. Let’s create a div with an id called “message_display” for this purpose:
<div id="message_display"></div>
Now for the final piece of the puzzle: To show our message when a user selects an option, we must assign the change() event of #item_select with the message display. Then we must assign the value of the option selected as the index of the message we want to display. Here is how to do it:
<script type="text/javascript">
var message = new Array();
message[1] = "You have selected first item";
message[2] = "You have selected the second item";
message[3] = "You have selected the last item";
$(document).ready(function(){
$("#item_select").change(function()
{
var message_index
message_index = $("#item_select").val();
$("#message_display").empty();
if (message_index > 0)
$("#message_display").append(message[message_index]);
});
});
</script>
The important thing to note here is that we must empty() the #message_display div or else the messages will keep on stacking due to the append() command.
That is all for the tutorial for today.
You can download the sample demo here:
Select Boxes and change() event demo









