By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,905 Members | 879 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,905 IT Pros & Developers. It's quick & easy.

How can I code to get more than One value from checkbox?

P: n/a
Hi,

I'm a newbie that just started to learn python, html and etc. I have
some questions to ask and hope that someone can help me on.

I'm trying to code a python script (with HTML) to get values from a
html form that consists of about 10 checkbox and a textbox where user
have to key in a value to perform a search.

From python tutors, I learned that I have to use the following method:

###
qtype = data.getfirst('qtype') ---- checkbox name
qtext = data.getfirst('qtext', '') ---- textbox name
###

but I don't really know how to do it. Should I use qtype =
data.getlist('qtype') to get the value from the checkbox and how to?
Currently, my method required me to type in every possible combination
of the checkbox and I know that this is wrong. I wanna to include
%(qtype) in my query statement so that the script will look for the
value that contain qtype everytime a form is processs but the way I'm
doing now is wrong.

query = "select %(qtype)s from shot_descriptions where
shot_number=%(qtext)s", qtype, qtext
Thus, can someone help me on this.

Thank you for any help.

Shufen
Jul 18 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Shufen wrote:
Hi,

I'm a newbie that just started to learn python, html and etc. I have
some questions to ask and hope that someone can help me on.

I'm trying to code a python script (with HTML) to get values from a
html form that consists of about 10 checkbox and a textbox where user
have to key in a value to perform a search.

From python tutors, I learned that I have to use the following method:

###
qtype = data.getfirst('qtype') ---- checkbox name
qtext = data.getfirst('qtext', '') ---- textbox name
###

but I don't really know how to do it. Should I use qtype =
data.getlist('qtype') to get the value from the checkbox and how to?
Currently, my method required me to type in every possible combination
of the checkbox and I know that this is wrong. I wanna to include
%(qtype) in my query statement so that the script will look for the
value that contain qtype everytime a form is processs but the way I'm
doing now is wrong.

query = "select %(qtype)s from shot_descriptions where
shot_number=%(qtext)s", qtype, qtext
Thus, can someone help me on this.

Thank you for any help.

Shufen


I think you're confusing checkboxes and radio buttons.

If you have ten different boxes that can be checked, each will usually
have a different name, so you can test them with data.getfirst("box1"),
data.getfirst("box2"), and so on.

While it's true that you can have several checkbox elements with the
same name, and that the CGI interface will give you a list of such
values, there's absolutely no need to do so and, as you have discovered,
it's positively unhelpful in most cases.

With radio buttons, you give each member of the set the same name in
your HTML and the browser submits the value of only the one that's been
checked (if one has).

regards
Steve
Jul 18 '05 #2

P: n/a
Steve Holden <st***@holdenweb.com> wrote in message news:<6J07d.1812$gk.1795@okepread01>...
I think you're confusing checkboxes and radio buttons.

If you have ten different boxes that can be checked, each will usually
have a different name, so you can test them with data.getfirst("box1"),
data.getfirst("box2"), and so on.

While it's true that you can have several checkbox elements with the
same name, and that the CGI interface will give you a list of such
values, there's absolutely no need to do so and, as you have discovered,
it's positively unhelpful in most cases.

With radio buttons, you give each member of the set the same name in
your HTML and the browser submits the value of only the one that's been
checked (if one has).

regards
Steve


Hi Steve,

I did that with reference to this:
http://www.python.org/doc/current/lib/node404.html

I used checkboxes because I wanna the user to be able to select one or
more of the checkboxes, these checkboxes have the same "name" - qtype
and different "value". For radiobuttons, the user can only choose one
of the given radiobuttons which is not what I want. Sorry, I think I
didn't make myself clear enough.
The following is my script:

################################################## #############################
#!/usr/bin/env python
#Created on: 30/09/04
#Help from Lee Harr and Danny Yoo - Python Tutor

import sys, os
import cgi
import cgitb; cgitb.enable()
import pg

def form():
print """<form method="post" action="">
<p>
<input type=checkbox name="qtype" value="all" checked />
All<br />
<input type=checkbox name="qtype" value="project" />
Project<br />
<input type=checkbox name="qtype" value="date_string" />
Date<br />
<input type=checkbox name="qtype" value="blame" />
Blame<br />
<input type=checkbox name="qtype" value="notes" />
Notes<br /></p>

<p>Search by shot number:<br>
<input type=text name="qtext" value="" />
<input type="submit" value="SEARCH" />&nbsp;
<input type="reset" value="RESET" /><br />
</form>"""

print "Content-Type: text/html\n\n"
print "<head><title>Searching by using Shot
Number</title></head><body>"

if __name__ == "__main__":

data = cgi.FieldStorage()

if data:
qtype = data.getfirst('qtype')
qtext = data.getfirst('qtext','')

for qtype in data.getlist('qtype'):
print "You typed in Shot Number:", qtext

#Will take care of the security problem later...
username = os.environ.get('USER')
if username == None:
username = 'apache'

#Now, we can get to the database...
db = pg.connect("moncdata", user=username, passwd=None)

#This is the part that I'm not sure of...please help...
query = "select %(qtype)s from shot_descriptions where
shot_number=%(qtext)s", qtype, qtext
qresult = db.query(query)

listOfResults = qresult.dictresult()

print """<p>Example of pulling the list of dictionary
results apart.</p>"""
for record in listOfResults:
print "<p><table>"
for k in record.keys():
print '<tr>'
print '<td>key:</td> <td>', k, '</td>'
print '<td>value:</td><td>', record[k], '</td>'
print '</tr>'
print '</table></p>'

db.close()

#Somehow, this part didn't work too, when I didn't input a
value
#it doesn't show this msg. Please help me on this part too.
Thks.
else:
print "You have no enter a shot number!"
print "Please type a in shot number in order to perform a
search!"

else:
form()
print "</body></html>"

################################################## #############################

Thank you in advance for any help.

Shufen
Jul 18 '05 #3

P: n/a
Shufen wrote:
Steve Holden <st***@holdenweb.com> wrote in message news:<6J07d.1812$gk.1795@okepread01>...

I think you're confusing checkboxes and radio buttons.

If you have ten different boxes that can be checked, each will usually
have a different name, so you can test them with data.getfirst("box1"),
data.getfirst("box2"), and so on.

While it's true that you can have several checkbox elements with the
same name, and that the CGI interface will give you a list of such
values, there's absolutely no need to do so and, as you have discovered,
it's positively unhelpful in most cases.

With radio buttons, you give each member of the set the same name in
your HTML and the browser submits the value of only the one that's been
checked (if one has).

regards
Steve

Hi Steve,

I did that with reference to this:
http://www.python.org/doc/current/lib/node404.html

I used checkboxes because I wanna the user to be able to select one or
more of the checkboxes, these checkboxes have the same "name" - qtype
and different "value". For radiobuttons, the user can only choose one
of the given radiobuttons which is not what I want. Sorry, I think I
didn't make myself clear enough.
The following is my script:

################################################## #############################
#!/usr/bin/env python
#Created on: 30/09/04
#Help from Lee Harr and Danny Yoo - Python Tutor

import sys, os
import cgi
import cgitb; cgitb.enable()
import pg

def form():
print """<form method="post" action="">
<p>
<input type=checkbox name="qtype" value="all" checked />
All<br />
<input type=checkbox name="qtype" value="project" />
Project<br />
<input type=checkbox name="qtype" value="date_string" />
Date<br />
<input type=checkbox name="qtype" value="blame" />
Blame<br />
<input type=checkbox name="qtype" value="notes" />
Notes<br /></p>

OK, it's not really obvious what this form is supposed to do for you. I
also don't understand whether it makes sense for "all" to be checked at
the same time as individual selections. But we'll leave that for now ...
<p>Search by shot number:<br>
<input type=text name="qtext" value="" />
It might make more sense to call this input "shotno" rather than
"qtext", but that won;t affect how the code functions.
<input type="submit" value="SEARCH" />&nbsp;
<input type="reset" value="RESET" /><br />
</form>"""
Aah, so we're looking up photographs in a database?
print "Content-Type: text/html\n\n"
print "<head><title>Searching by using Shot
Number</title></head><body>"

if __name__ == "__main__":
It's a bit too late for this if you've already written the headers out,
I should say - it would make more sense to move those prints above down
here so they don't get run if the script is imported.
data = cgi.FieldStorage()
Great!
if data:
qtype = data.getfirst('qtype')
Since the "for" statement below assigns to qtype, the statement above is
completely redundant.
qtext = data.getfirst('qtext','')

for qtype in data.getlist('qtype'):
So if you check "project" and "blame", you should iterate round this
loop twice, with qtype being set to "project" the first time and "blame"
the second.
print "You typed in Shot Number:", qtext

#Will take care of the security problem later...
username = os.environ.get('USER')
if username == None:
username = 'apache'

#Now, we can get to the database...
db = pg.connect("moncdata", user=username, passwd=None)
It doesn't make sense to connect to the database each time round the
loop (and I'm still not even convinced this loop is what you want...)
#This is the part that I'm not sure of...please help...
query = "select %(qtype)s from shot_descriptions where
shot_number=%(qtext)s", qtype, qtext
qresult = db.query(query)
I take it pg is some kind of PostGres interface? And AAH!!, now I see
that what the checkboxes are supposed to do is select fields for the
output. You appear to be missing a "percent" sign up there - it should
either be

query = "SELECT %s ...=%s" % (qtype, qtext)

or

query = "SELECT %(qtype)s ... =%(qtext)s" % data

to put the query type and the text into the string, depending on which
substitution method you want to use. You should really be testing a lot
of this stuff in an interactive copy of the interpreter (I hope you do
have Python available other than just on your web server).

Unfortunately the assignment to query isn;t a syntax error in Python
(you are just assigning a three-element tuple to query) but poor old
PostgreSQL isn;t going to know what to make of the result.

Do you want to see a separate chunk of output for each field, or do you
want to see the fields as columns of a table? The latter seems to make
more sense to me, but it would have been REALLY nice if this
conversation has started out like "I have a bunch of shot descriptions
is a database, and I want to be able to see just selected fields about a
shot".

For the structure you've got now it looks like you plan to loop around
the column names, doing a query for each one, and printing out a table
for each field. And we don't have any way to handle "all", by the way
.... unless that's just another database column.
listOfResults = qresult.dictresult()

print """<p>Example of pulling the list of dictionary
results apart.</p>"""
for record in listOfResults:
print "<p><table>"
for k in record.keys():
print '<tr>'
print '<td>key:</td> <td>', k, '</td>'
print '<td>value:</td><td>', record[k], '</td>'
print '</tr>'
print '</table></p>'

db.close()

#Somehow, this part didn't work too, when I didn't input a
value
#it doesn't show this msg. Please help me on this part too.
Thks.
The reason for that is that even when you don't enter anything into the
form the submit button still gets put in there as a data item, so the
form will never be truly empty.
else:
print "You have no enter a shot number!"
print "Please type a in shot number in order to perform a
search!"

else:
form()
print "</body></html>"

################################################## #############################

Thank you in advance for any help.

Shufen


OK, before we go any further I'd like you to tell me exactly what you;d
like this page to do. You probably aren't that far froma solution now,
but it would be nice to answer the right question.

I'm suspecting that what you really want is something like

query = """SELECT %s FROM shot-descriptions WHERE
shot_number=%s""" % (
data.getvalue("qtype"), data.getfirst("qtext"))

Since I have to go off and earn pennies now, someone else may be able to
help you in the interim. I'm likely to be off-net for a bit. Stick with
it, you're almost there!

regards
Steve
Jul 18 '05 #4

P: n/a
Hi,

Sorry I know this is kinda of long, but please give me a helping hand
if you understand what I'm looking for.

The following attached is my revised version of my code. I added some
stuffs into it and now it can really run - error (I supposed my method
is wrong again, but I hope my idea is there).

This is what is I have:
I have a bunch of stuffs in a database table named
"shot_descriptions".

And this is what I wanna my page to do:
The columns of this table consists of project name, date, shot number,
notes and etc. And these fields are the stuffs that I wanna to present
them in checkboxes form so that the user can select the number of
information they wanna to see in the results (output). And a textbox
for user to key in a specific shot number in order to perform a
search. So, if there is no input in the shot no textbox, an error msg
will show (this is one of the part that is not working now, please
help). I wanna to display the output in a table form and I'm currently
using dictionary to help me with this task. But I'm wondering is there
a better way to show it? I mean other than dictionary, how can I code
it so that the results will display nicely in a html type of table
with columns and rows instead of key: blah blah and value: blah blah.
If someone can help me on this part, it will be very nice, cos I'm
concern about the presentation of the output too.

Revised Version:
What I did is include a section where it will display an error msg
when no input is given. Besides, my code (earlier version) displayed
results in a repeated loop form when there is more than a tick in the
checkboxes.

It will show somthing like this:
You entered Shot Number: xxxx

key: xxxx value: xxxx

You entered Shot Number: xxxx

key: xxxx value: xxxx

And it just went on....depending the number of ticks.

Thus, in this revised version, I separated into 2 conditions.
Condition 1 taking care of more than one input and Condition 2 taking
care of only ONE input. But somehow, there is error in this code and I
suspected I did something very wrong again so please help me. I wonder
if there is any way to display the results in a nice table form for
Input that is more than ONE?

Any help is very very much appreciated.

I hope that will be someone responding to this as I took a long time
to figure out this revised code (I'm not good in programming - new)
and of cos to write this msg.

Thanks for any help.

Shufen
################################################## #############################
#!/usr/bin/env python
#Author: Chong Soo Fern
#Created on: 30/09/04
#Modified on: 02/10/04
#Help from Lee Harr, Danny Yoo and Steve - Python Tutor

import cgi, os, sys, string
import cgitb; cgitb.enable()
import pg

def form():
print """<form method="post" action="">
<table border="0" width="750" cellspacing="2"
cellpadding="2">
<tr><td width="150" align="left">
<input type=checkbox name="qtype" value="*" checked
/>All</td>
<td width="150" align="left">
<input type=checkbox name="qtype" value="project"
/>Project</td>
<td width="150" align="left">
<input type=checkbox name="qtype" value="notes"
/>Notes</td>
<td width="150" align="left">
<input type=checkbox name="qtype" value="date_string"
/>Date</td>
</table>

<p>Search by shot number:<br>
<input type=text name="shot_no" value="" tabindex="1" />
<input type="submit" value="SEARCH" tabindex="2" />
<input type="reset" value="RESET" tabindex="3" /><br />
</form>"""
if __name__ == "__main__":

print "Content-Type: text/html\n\n"
print "<head><title>Quick Search using Run
No</title></head><body>"

sys.stderr = sys.stdout
data = cgi.FieldStorage()

#Get the shot_no first, followed by each value of the checkboxes.
shot_no = data.getfirst("shot_no", "")
qtype = data.getvalue("qtype")
#I wanna to show the error msg if no input is given.
if not (data.has_key("qtype") and data.has_key("shot_no")):
print "You have not select an option!\n"
print "Please tick at least one checkbox provided!\n"
print "You have no enter a shot number\n!"
print "Please type a in shot number in order to perform a
search\n!"

#I don't know why this function kept showing error... please
advice
#Error: SyntaxError: 'return' outside function
return form()

if isinstance(qtype, list):

# Conditon 1: The user selected more than one qtype.
# Display the results in one way, different from condition 2.

print "You entered Shot Number:", shot_no

#Will take care of the security problems later...
#Defined a username and connect to the database...
username = os.environ.get('USER')
if username == "None":
username = "apache"

db = pg.connect("moncdata", user=username, passwd=None)
query = """SELECT %s FROM shot_descriptions WHERE
shot_number=%s""" % (qtype, shot_no)
qresult = db.query(query)
listOfResults = qresult.dictresult()
print listOfResults

db.close()

else:

# Condition 2: The user selected only ONE qtype.
# Display the results in another way.
# I don't want each qtype to showed in sort of a repeated
results loop way.

print "You entered Shot Number:", shot_no

#Will take care of the security problems later...
#Defined a username and connect to the database...
username = os.environ.get('USER')
if username == "None":
username = "apache"

db = pg.connect("moncdata", user=username, passwd=None)
query = """SELECT %s FROM shot_descriptions WHERE
shot_number=%s""" % (qtype, shot_no)
qresult = db.query(query)
listOfResults = qresult.dictresult()
print """<p>Example of pulling the list of dictionary results
apart.</p>"""
for record in listOfResults:
print "<p><table>"
for k in record.keys():
print '<tr>'
print '<td>key:</td> <td>', k, '</td>'
print '<br />'
print '<td>value:</td><td>', record[k], '</td>'
print '</tr>'
print '</table></p>'

db.close()

print "</body></html>"

################################################## #############################
Jul 18 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.