Hey ya guys. just want to share this piece of useful hack just in case you might need it.
Problem: Have you ever wanted to display a text in <select> that is not found on the select's <option>'s?
Solution:
What i did here was i have a select with grouped options. upon selection of an item in the select element, i wanted to display it such that the Label of the optgroup and the option text is displayed together. it's a rough solution so suggestions would be welcome.
Javascript Code
Code:var oldList = ''; function delList(obj){ for ( i = obj.length-1; i >= 0; i--){ obj.remove(i); } } function addOptionInList(list,text,value){ var elOptNew = document.createElement('option'); elOptNew.text = text; elOptNew.value = value; try { list.add(elOptNew, null); // standards compliant; doesn't work in IE } catch(ex) { list.add(elOptNew); // IE only } } //Modes: //0: Display Original List //1: Display Changed List function changeList(obj,event){ if ( oldList == '' ){ oldList = obj.innerHTML; } mode = document.getElementById('mode').value; selectedIndex = document.getElementById('selectedIndex'); if( mode == "0" && event == "focus"){ // fire onClick obj.innerHTML = oldList; document.getElementById('mode').value = 1; obj.selectedIndex = selectedIndex.value; } else { // fire onChange if( event == "change"){ selectedIndex.value = obj.selectedIndex; parent = obj[obj.selectedIndex].parentElement if(!parent){ parent = obj[obj.selectedIndex].parentNode } label = parent.label; value = label+', '+obj.value; text = label+', '+obj.value; delList(obj); addOptionInList(obj,text,value); document.getElementById('mode').value = 0; obj.blur(); } } }here's a link for the output.:http://jsfiddle.net/gqpp9/1/embedded/result/HTML Code:<input type=hidden id=mode value='1'> <input type=hidden id=selectedIndex value='0'> <select id=sel onchange="changeList(this,'change');" onfocus="changeList(this,'focus');"> <optgroup label="Car"> <option>Volvo</option> <option>Saab</option> <option>Mercedes</option> <option>Audi</option> </optgroup> <optgroup id=motorcycle label="Motorcycle"> <option>Harley</option> <option>Suzuki</option> <option>Honda</option> <option>Ninja</option> </optgroup> </select>
any comments/suggestions for improvement are welcome.




Reply With Quote
