Adding an onchange method to a field in a form

4,569 views
Skip to first unread message

Tom Badran

unread,
Feb 19, 2008, 2:40:56 PM2/19/08
to Django users
Using django newforms, is there a nice way i can add an onchange method to just one field of the form?

At the moment, instead of doing:

{{ form.as_table }}

 im doing:

<label id="whatver>Field:</label>{{ form.field }}

for all my fields, and just manually entering the one with the onclick into the template. It feels like i'm missing something completely obvious here, but its been a long day, and i've already spent most of it learning javascript, so now my brain has shut off.

Thanks for any pointers.

Tom

--
Tom Badran
http://badrunner.net

Jonathan Buchanan

unread,
Feb 19, 2008, 3:12:15 PM2/19/08
to django...@googlegroups.com

Use JavaScript in your template to add the onchange handler:

<script type="text/javascript">
window.onload = function()
{
document.getElementById("id_yourfield").onchange = function()
{
doStuff();
};
};
</script>

If you're using a JavaScript library, it will no doubt have a more
succinct way to do this which registers the event handler properly
instead of assigning a function to an event property.

Jonathan.

Tom Badran

unread,
Feb 19, 2008, 3:41:35 PM2/19/08
to django...@googlegroups.com
Exactly what i needed, thanks

Tom

Meista

unread,
Feb 19, 2008, 3:53:00 PM2/19/08
to Django users
Putting a line like
field.widget.attrs["onchange"]="JavaScript_here()"
into your the form definition works for me, too.



On 19 Feb., 21:41, "Tom Badran" <t...@badrunner.net> wrote:
> Exactly what i needed, thanks
>
> Tom
>
> On Feb 19, 2008 8:12 PM, Jonathan Buchanan <jonathan.bucha...@gmail.com>
> --
> Tom Badranhttp://badrunner.net
Reply all
Reply to author
Forward
0 new messages