简体   繁体   English

web2py:如何将javascript添加到Web2py Crud表单?

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

Working with Web2Py. 使用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. 我试图将一些JavaScript附加到字段(onchange)或表单(onsubmit)上,但是我绝对看不到将此类参数传递给crud.create或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. 合适的方法是让web2py邮件列表中的人知道如何使用,而不是一般的堆栈溢出用户会猜出错误的答案。 :-) :-)

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). Element采用css3 / jQuery语法(但在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. 一种选择是仅操作web2py生成的HTML,它只是一个字符串。 Even cleaner, in my opinion, is just to bind the event using jQuery's $(document).ready() function. 在我看来,更干净的方法就是使用jQuery的$(document).ready()函数绑定事件。

Say you have a database table (all is stolen from web2py's docs): 假设您有一个数据库表(所有内容都从web2py的文档中被盗):

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): 并且您想要向名称输入字段添加onblur处理程序(添加到视图):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM