0

I have next form:

class ExampleForm(forms.ModelForm):
  class Meta:
     model = ExampleModel
     fields = ['field1', 'field2', 'field3']
     widgets = {'field1': forms.Select(attrs={'onchange': 'onchangeJsFunction()'})}

So far i have been able to add onchange property to my select field that calls 'onchangeJsFunction()' every time 'field1' value is changed. My next goal is to add a function that is going to be executed every time form is loaded, and i am not sure how to do it. I have tried adding onload property to a input field this way:

...
widgets = {'field_2': forms.TextInput(attrs={'onload': 'onloadJsFunction();'})}
...

but it does not give any results so far.

How am i supposed to execute certain JS function every time my Django Form is loaded?

2
  • 1
    Can't you add it to the <body> tag? Commented Feb 11, 2023 at 9:42
  • If i add it to my body tag, the function is going to be called only once - when the page is loaded. The thing is that my form is within hidden bootsrap modal window, and that modal window, with form, shows when certain button is pressed on webpage. Commented Feb 11, 2023 at 9:50

1 Answer 1

1

Based on the comment that you are using a bootstrap modal - you could add an event listener to the modal that runs code when it is is shown

In bootstrap 4 (jquery)

$('#myModal').on('shown.bs.modal', function () {
 //onloadJsFunction() or similar
})

in bootstrap 5

var myModal = document.getElementById('myModal')

myModal.addEventListener('shown.bs.modal', function () {
  ////onloadJsFunction() or similar
})

(tweaked from bootstrap docs)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.