views:

451

answers:

2

Hee guys. I have a form with a dropdown for all companies. Now i want to display all the people that work for that company when the user changes the value in the company dropdown box without hitting the submit button on the form. Anybody have a good example for that?

tks

+3  A: 

No Ajax necessarily needed, since you can just submit the form, and whether you're sing Django or other server-side choices make no difference, just use something like...:

<form name=companiesForm action="whateverurl" method=POST>
  <p>
  <select name=companySelect size=1 onChange="companiesForm.submit();">
    <option value="" SELECTED>Choose A Company
    <option value="1">One Company
    <option value="2">Another Company
    <option value="3">A Third Company
  </select>
  </p>
</form>
Alex Martelli
+2  A: 

Alex's answer is a good route to go, but here's an alternative. Django and slugs go together rather well. And unobtrusive javascript with jquery is hip at the moment.

Instead of POSTing a value, you could simply navigate to a well-constructed URL. This has the added benefit of making the pages more SEO friendly, letting people bookmark the page, and also avoiding that silly error about POST'ed information when someone clicks the back button.

Note that in either bit of code, Alex's or mine, the navigation will break if javascript is disabled on the client browser. It'd be a good idea to provide some footer links to whatever this combo box does somewhere on the page (the bottom maybe).

(untested, might need some slight tweaks)

<!-- you'll need jquery to make this work -->
<script type="text/javascript">
     $(function() {
          // navigate to page on click event
          $('#nav_combo').bind('change', function() { goToPage(); } );
     });

     function goToPage() {
      var baseUrl = '/your/base/url/';
      window.location.href = baseUrl + $('nav_combo').val()
     }
</script>

...

<form>
     <select id="nav_combo">
          <option value="page-1-slug">Page 1</option>
          <option value="page-2-slug">Page 2</option>
     </select>
</form>

Edit -- By the way, I should have mentioned you could easily use the code above plugged into django's object_detail generic view.

T. Stone
Interesting concept, +1
TM