开发者

web2py: How do I add javascript to Web2py Crud form?

开发者 https://www.devze.com 2023-01-31 18:28 出处:网络
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 a开发者_运维问答rgument to crud.create or to

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 a开发者_运维问答rgument to crud.create or to form.custom.widget.

Anyone has an idea?


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).


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消