Home > Back-end >  Adding Alpine attributes to Django's form fields
Adding Alpine attributes to Django's form fields

Time:08-22

I'm rendering django template form fields this way :

<div x-data="{ amount: 0 }">
    {% render_field field class=class %}
</div>

I want to add to the input : x-on:input.change="console.log('test');"

  1. How can I add this to render_field ?
    In forms.py as
    widgets = { 'amount': forms.TextInput(attrs={'x-on:input.change': "console.log('test');" }) }
    the only way ?

  2. Is there a way to add x-on:input.change via JavaScript ?

CodePudding user response:

You can add:

attrs={'onChange':"yourJavaScriptFunction(this.id)"} #You can pass arguments about 'this', for example.

Then just add the function in your template, or js.

  • Related