How can i add a onchange js event to Select widget in Django?

10,263

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)
}
Share:
10,263
Abhijith K
Author by

Abhijith K

Working to make the dreams to reality.

Updated on June 13, 2022

Comments

  • Abhijith K
    Abhijith K almost 2 years

    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))
    
    • hansTheFranz
      hansTheFranz over 6 years
      JS functions are done on the frontend. Try to trigger the click event.
    • Abhijith K
      Abhijith K over 6 years
      In the template file , the code for Select option is {{receipt}}. where should i add the js script.
  • Lotte
    Lotte about 3 years
    if I have an external javascript file, with myFunction script, how would I correctly point it in forms.py?