Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I need to attach a JavaScript onchange event to the receipt dropdown list in a Django project. When the value of the dropdown list is changed a JavaScript function is to be called. How can it be done? The form.py file is given below

from django import forms
receipt_types=(('option1','Option 1'),('option2','Option 2'),('option3','Option 3'),)
class accountsInForm(forms.Form):
    receipt=forms.CharField(max_length=100, widget=forms.Select(choices=reciept_types))
                In the template file , the code for Select option is {{receipt}}. where should i add the js script.
– Abhijith Konnayil
                Sep 9, 2017 at 10:15

Change the code as follows :
reciept=forms.ChoiceField(reciept_types, widget = forms.Select(attrs = {'onchange' : "myFunction();"}))

In case you want to have access to the input value in your JavaScript code, which is very common:

{'onchange' : "myFunction(this.value);"}

And the JS:

myFunction(value) {
    console.log(value)
                if I have an external javascript file, with myFunction script, how would I correctly point it in forms.py?
– Lotte
                Mar 2, 2021 at 20:17
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.