English 中文(简体)
How to set an event handler in a Django form input field
原标题:

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.

最佳回答

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
问题回答

What I do for that is :

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

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

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.

The Ghislain Leveque answer works to me, but in django 1.9 I did it like this:

class myForm(forms.ModelForm):
    class Meta:
        model = USER
        fields = ["password", "idCity"]
        widgets = {
            "password": forms.PasswordInput(),
            "idCity": forms.Select(attrs={ onchange : "alert( foo ! );"})
        }

I took JQuery approach using Ghislain Leveque s answer. This way I was able to trigger the event handler on page load.

class MyForm(forms.Form):
    stuff = forms.ChoiceField(
        [( a , A ),( b , B )],
        widget = forms.Select(attrs = {
             widget_to_bind  : "True",
            }
        )

In my javascript:

function myFunction() {
    var source = $(this); // Widget element
}

$( [widget_to_bind=True] ).change(myFunction);
$( [widget_to_bind=True] ).trigger("change");

Variation on a theme:

class CategoriesForm(forms.Form):
stuff = forms.MultipleChoiceField(
    choices=([(pt.id, pt.name) for pt in PaymentType.objects.order_by( name )]),
    widget=forms.SelectMultiple(attrs={ size :  20 ,  class :  mc_payment_type })
    )

JQuery:

<script language="javascript">
    $( .mc_payment_type ).change(function () {
        console.log( payment type selected:   + $(this).find( option:selected ).val());
</script>




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签