1

I have a Django form with a number of dropdown menus, all of CharFields (before we go further--I think this problem could be solved with some additional models and some M2M relationships, but that idea has been squashed by the Powers That Be). I want to use javascript (ajax?) to change the options in the second field based on the value of the first.

Right now, I'm struggling with how to change the values at all. I have this:

<script>
$('#id_database_type').change(function(){
  $('.asset-form').fields['monitoring_method'].widget.choices=[('test', 'test')]
});
</script>

but I'm getting an undefined error; $('.asset-form').fields returns undefined. This was code I got from another post but I think it is supposed to go in the init section of my form, which I don't think would do what I want it to do.

thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
  • You seem to not understand the distinction between server side code and client side code. Take a look at [my answer here](http://stackoverflow.com/questions/20952156/how-to-pass-javascript-variable-to-django-custom-filter/20952666#20952666). It doesn't answer your particular question, but may make the destination clearer, and help you understand why your code can not work. – Ludwik Trammer Feb 24 '14 at 21:38
  • No, I didn't expect my code to work. I just can't figure out what it should be instead. – thumbtackthief Feb 24 '14 at 21:39
  • This code attempts to manipulate server-side data structures on the client side - long after Django rendered the page and stopped handling the particular request. To change select options on the client side you need to manipulate browser DOM, and that has nothing to do with Django. I still can't help but think you are somewhat confused about the distinction, but that's obviously for you to decide. – Ludwik Trammer Feb 24 '14 at 21:46
  • I think you are arguing semantics with me. I thought it was at least relevant that django was used to create the form. If it's not, fine. Now that I have the form, my question is: how do I use javascript to alter those values? – thumbtackthief Feb 24 '14 at 21:47
  • (As I mentioned, I had no real hope that the code I posted would work, for the very reasons you're talking about. I just know better than to come here without any code at all to show.) – thumbtackthief Feb 24 '14 at 21:49
  • You can find answer to your particular question about changing select options on the client side [here](http://stackoverflow.com/questions/1801499/how-to-change-options-of-select-with-jquery). – Ludwik Trammer Feb 24 '14 at 22:00

0 Answers0