Creating a Jumpmenu in jQuery

I ran across an article at A Beautiful Site today while trying to find a nice javascript jumpmenu code today to replace my bookmarked antiquated version.  The javascript code I found there was very well done and geared toward unobtrusiveness, which is always a good thing.  I grabbed the code and put it into my text editor:

<script type="text/javascript">
    function 
initJumpMenus() {
        
// Turns all <select> elements with the 'jumpmenu' class into jump menus
        
var selectElements document.getElementsByTagName("select");
        for( 
0selectElements.lengthi++ ) {
            
// Check for the class and make sure the element has an ID
            
if( selectElements[i].className == "jumpmenu" && document.getElementById (continued...)
                     (
selectElements[i].id) != "" {
                jumpmenu 
document.getElementById(selectElements[i].id);
                
jumpmenu.onchange = function() {
                    
if( this.options[this.selectedIndex].value != '' {
                        
// Redirect
                        
location.href=this.options[this.selectedIndex].value;
                    
}
                }
            }
        }
    }
   
    window
.onload = function() {
        initJumpMenus
();
    
}
</script>

Just add class="jumpmenu" to the select box and you are good to go. 

However, as I read through the code, I noticed that most of what was happening was selecting and evaluating the value of the select box.  I decided that I could easily rebuild this function in jQuery with a lot less code, and the resulting code would be more readable.  As well, jQuery was already put to use on most pages of my site for other reasons, so creating the jumpmenu in jQuery made perfect sense. 

Of course we need the requisite jQuery call, and to make this super easy, I will also include the great Selectboxes plugin from TexoTela.  This plugin allows us to easily get a selectbox value, as well as some other functions that we won’t use here. Here is the simple code:

<script type="text/javascript" src="/js/jquery.js" charset="utf-8"></script>
<script type="text/javascript" src="/js/jquery.selectboxes.js" charset="utf-8"></script>
<script type="text/javascript">
<!--
//on page load
$(document).ready(function() {
    
$(".jumpmenu").change(function() {
        
var val = $(this).selectedValues();
        if (
val != ''{
            location
.href=val;
        
}
    }
);
});
-->
</script>

As with the original code, simply add class="jumpmenu" to your selectbox and it should work for you.  Good luck!

Leave a Comment

 Remember Me?

 Notify Me of Follow Up Comments?

Article Information

Archive Distractions