views:

326

answers:

4

How to set a JavaScript function as handler in the event onclick in a given field of a Django Form. Is this possible?

Any clue would be appreciated.

A: 

I would recommend looking at using a JavaScript library such as jQuery. Here is the link to binding the click event in jQuery. Since Django names all of the input fields you can connect my_field_name in your Django form to the click event like so:

$("form input[name='my_field_name']").click(function () { 
    // Handle the click event here
});
Mark Lavin
+1  A: 

If you are looking for automating this process, you can create a custom widget for the field. In the widget class you will define a render method in such a way that it will also return the event binding code.

class CustomWidget(forms.TextInput):

    class Media:
        #js here
        js = ('js/my_js.js',)

    def render(self, name, value, attrs = None)
         output = super(CustomWidget, self).render(name, value, attrs)
         #do what you want to do here
         output += ...
         return output
shanyu
+1  A: 

What I do for that is :

class MyForm(forms.Form):
    stuff = forms.ChoiceField(
        [('a','A'),('b','B')],
        widget = forms.Select(attrs = {
            'onclick' : "alert('foo !');",
            }
        )
Ghislain Leveque
A: 

Using YUI, you can do that like this:

YAHOO.util.Event.addListener(id_myField, "click", myClickEventHandler, myOptionalData);

See also YUI 2: Event Utility

I prefer using a JavaScript library, as this keeps browser-side JS code nicely separated from server-side Django.

ssc