2

Working with Web2Py. I'm trying to attach some javascript either to a field (onchange) or to the form (onsubmit), but I see absolutely no way to pass such argument to crud.create or to form.custom.widget.

Anyone has an idea?

2 Answers 2

4

Of course there is a way. The appropriate way is to ask people on the web2py mailing list who know how to, as opposed to generic stack overflow users who will guess an incorrect answer. :-)

Anyway, assume you have:

db.define_table('image',
    Field('name'),
    Field('file', 'upload'))

You can do

def upload_image():
    form=crud.create(db.image)
    form.element(name='file')['_onchange']='... your js here ...'
    form.element('form')['_onsubmit']='... your js here ...'
    return dict(form=form)

Element takes the css3/jQuery syntax (but it is evaluated in python).

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

3 Comments

my apologies, just trying to help and I thought I was a pretty savy web2py user (I did the taskbar widget). I wouldn't dismiss stackoverflow over mailing lists, stackoverflow is a lot more fun :)
@Mark, no apologize needed. Your answer was good. It does solve the problem effectively. I am not convinces that the controller is in fact the right place to set these attributes. @Bob, element is in the docs but the examples use other attributes, not onchange and onsubmit.
this worked for me: using form.element(_name='file') (notice the underscore in _name )
0

I do not believe there is a way to do this directly. One option is just to manipulate web2py generated HTML, it is just a string. Even cleaner, in my opinion, is just to bind the event using jQuery's $(document).ready() function.

Say you have a database table (all is stolen from web2py's docs):

db.define_table('image',
    Field('name'),
    Field('file', 'upload'))

With form:

def upload_image():
    return dict(form=crud.create(db.image))

Embedded in a view (in the simplest manner):

{{=form}}

And you want to add an onblur handler to the name input field (added to the view):

<script type="text/javascript">
$(document).ready(function(){
    $("#image_name").blur(function(){
      // do something with image name loses focus...
    });
});
</script>

1 Comment

Thanks for the idea, it might be useful for other cases.

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.