The Data Asylum

Programming, Databases and People

Working With Select Boxes Using JQuery

Using standard javascript, working with select boxes is uncomfortable, at best. Typically you want to see which value has been selected. How many times have you written the following code and wished there was a quicker way.

1
2
var selObj = forms.surveyform.selectBox;
value = selObj.options[selObj.selectedIndex].value;

jQuery makes this much simpler.

There is the standard val() function which you can use on any form field. The basic premise of jQuery is that you first select an html element and then perform an action on it.

1
2
3
4
5
<select name='selectBox'></select>
...
<script language='javascript'>
  var value = $('select[name=selectBox]').val();
</script>

If you want to make this simpler, you can give the select box an id.

1
2
3
4
5
<select name='selectBox' id='selectBox'></select>
...
<script language='javascript'>
  var value = $('#selectBox').val();
</script>

Another common need is to get the label of the selected item i.e. what the user can see. In this case you need to select the selected option, and get the text value of it.

1
var label = $('#selectBox :selected').text();

This is just one example of how to use a javascript framework to be more productive.