Given this form:
form = SQLFORM.factory(
Field('name'),
Field('created','date'),
Field('owner'),
Field('cat',requires=IS_IN_SET(range(0,6))))
This will produce these form elements:
<input type="text" value="" name="name" id="no_table_name" class="string"/>
<input type="text" value="" name="created" id="no_table_created" class="date"/>
<input type="text" value="" name="owner" id="no_table_owner" class="string"/>
<select name="cat" id="no_table_cat" class="string">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" value="Submit"/>
You can grab any of them using the element and elements function. Both of these functions accept any combination of tag names and attributes.
For example, this will grab the text input produced for the name Field.
form.element('input',_name='name')
This will grab all of the text inputs:
form.elements('input',_type='text')
Let's add a secondary class to all elements with a string class:
strings = form.elements(_class='string')
for s in strings:
s['_class'] = 'string myclass'
Let's add a confirmation to the submit button:
submit = form.element("input",_type="submit")
submit["_onclick"] = "return confirm('Are you sure?');"
That's it!
Comments (4)
0
aleksdj 15 years ago
0
select 14 years ago
0
tobias 10 years ago
Very useful, thank you! Was searching in the documentation for a while for how to do this and found your page when I just googled "web2py add class attribute to form field"
0
kendo 8 years ago
Muchas gracias