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

余生颓废 提交于 2020-05-16 06:05:08

问题


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))

回答1:


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)
}


来源:https://stackoverflow.com/questions/46124531/how-can-i-add-a-onchange-js-event-to-select-widget-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!