Prototype – get selected element from non-unique select box

These days I’m working a lot with other people’s code, I just discovered that a selectbox whose currently selected option I want to retrieve the inner html from; has the same id as a table column higher up in the document. Great…

The code in is using Prototype and this is how the problem can be solved:

function getSelected(select_box){ 
    for(var i = 0; i < select_box.options.length; i++){
        var curOpt = $(select_box.options[i]);  
        if(curOpt.readAttribute('selected') == "selected")
            return curOpt.innerHTML; 

function sendToCountry(){
	var goTo = '/admin/sendmail/?to_country='+getSelected($$('.admin_search_p #country').first());
	window.location.href = goTo;	

The sendToCountry() function is the entry point. We use Prototype’s CSS selector by going $$ instead of just $. The select box with id country (which is also the id of a td higher up) has a parent with the style admin_search.

Note that the $$ selector will return a Prototype array and we only want one element, the first one, so we go first() on the collection.

Then we loop through all the options and convert them one by one to a Prototype object which we can call readAttribute() on to check if selected has something or not. If it has we simply return the innerHTML and are done. Finally we use window.location.href to go where we want to, passing the selected country’s name in the GET variables.

Why didn’t I simply change the id of the select box? Well when you work with other people’s code you should be careful of changing stuff that is already there, especially stuff like ids…

Related Posts

Tags: , , ,