Integrating freeform <select> with JavaScript and CSS

At work I have an application that requires a user to select a choice from a drop down box or a <select> control for the HTML savvy. As far as I know (or could find) there is no such control in HTML 4.01 that allows both a select box with the added bonus of taking free form user input. So to meet the needs of this project I crafted one up using CSS and JavaScript. This is my first dive into CSS/JS in a while so be gentle.

I accomplished this by creating two elements (SELECT & INPUT) and then switching the elements visibility properties.

<script type="text/javascript" >
function showOther(id, id2){
  if(id.options[id.selectedIndex].label == "Other"){
   id.style.visibility = "hidden";
   id2.style.visibility = "visible";
  }
}
</script>
<select id="sel1" onChange="showOther(sel1, inp1)"
style="position:absolute; left:10; top:10;" >
  <option value="0" label=""></option>
  <option value="1" label="Choice1">Choice1</option>
  <option value="2" label="Choice2">Choice2</option>
  <option value="3" label="Other">Other</option>
</select>
<input type="text" id="inp1" style="visibility='hidden'"
style="position:absolute; left:10; top:10;" />

To see it in action go here

About Jon

Recently a student. Now a professional. Fighting my way upstream!
This entry was posted in Code, Programming, Web Design, Work and tagged , . Bookmark the permalink.

5 Responses to Integrating freeform <select> with JavaScript and CSS

  1. todd says:

    What you want is an auto-completion script…

    e.g. like this:
    http://www.google.com/webhp?complete=1&hl=en

    where you start with a text box, but typing something, presents the potential matching items…

  2. jon says:

    Yeah I do like that feature as well. For the application in which that came from, that input was for medicine names (for Dr use) so we thought the list of choices would be the best. But thanks for the link. Much appreciated.

  3. Hrm, but now if you accidentally choose “other” you’re stuck.

  4. jon says:

    @ Will
    Yup.
    I’ve since changed the code to include ondblclick within the input box.
    Now when the user double clicks in the input box the select will once again be visible.

    I plan on taking that a step further so it is a little more intuitive. I should post it within the week.

  5. Wahoo says:

    Thank you for sharing!