14 May 2010

Code, Tech

Select Menus and Conditional Logic with jQuery

In a recent prototype for a web application we are working on, we needed to use a select menu to display the appropriate result after a user makes a selection. We couldn’t find any jQuery examples online that did just what we wanted, so hopefully the following will help someone facing the same problem.

Here’s an example of what we want to happen. Choosing one of the options in the select menu reveals a particular paragraph. Clicking “Remove” makes that paragraph disappear again. Choosing “Select...” resets everything back to where we started:

And here’s how the code works. First include jQuery (duh). Next create a select menu with a value included for each option. (That’s crucial for making the whole thing work.) Following that, we’ve got three hidden paragraphs, each with an id (unique, of course). Then comes the script, which pretty much says “If the user switches the select menu to option 1, 2, or 3, display the corresponding paragraph. If they select the first option, hide any displayed paragraphs. And if they click a link, hide the parent (the paragraph in this case) of that link.” Hope that helps, and happy coding:

<!DOCTYPE html>

  <script type="text/javascript" src=""></script>

    <option value="0">Select...</option>
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
  <p id="first" style="display: none">This is the first paragraph. <a class="remove" href="#">Remove</a></p>
  <p id="second" style="display: none">This is the second paragraph. <a class="remove" href="#">Remove</a></p>
  <p id="third" style="display: none">This is the third paragraph. <a class="remove" href="#">Remove</a></p>
    $('select').change(function() {
      if ($(this).val() == 1) {
        $('#first').show('fast'); }
      else if ($(this).val() == 2) {
        $('#second').show('fast'); }
      else if ($(this).val() == 3) {
        $('#third').show('fast'); }
      else if ($(this).val() == 0) {
        $('#first, #second, #third').hide('fast'); }

    $('.remove').click(function() {

1 Comment

Posted by
15 May 2010 @ 10am

Slick! Can’t wait to see what you’re building this for…

Leave a Comment