I am messing around with a tornado web app with which I need a bit of help. I have multiple checkboxes with the same name and I would like to POST the values of the selected one.
<input id=DB_BASED_ID name="activity" value=DB_BASED_ID type="checkbox"/>
<input id=DB_BASED_ID name="activity" value=DB_BASED_ID type="checkbox"/>
<input id=DB_BASED_ID name="activity" value=DB_BASED_ID type="checkbox"/>
<input id=DB_BASED_ID name="activity" value=DB_BASED_ID type="checkbox"/>
I can get the values of each with javascript pre-POST but am having troubles getting this list on the python (tornado) side. i only get the highest selected value.
on the python side it looks like:
...
def post(self):
开发者_运维技巧email = self.get_argument("email")
activity = self.get_argument("activity")
It's fine to let multiple tags have the same name attribute, but the id
attributes must be unique -- here, they're not (unless each of those occurrences of the identical DB_BASED_ID
is somehow meant to be replaced with a different value? But then why not show the things actually distinct, as they do appear in the real HTML?!), making this invalid HTML and subject to all sorts of problems.
Once this problem is fixed, in those handler methods, self.request.arguments['activity']
(if that string key is present in said directory) will be a list of non-empty values for all inputs named 'activity'
(if any).
This can also be accomplished with a loop for dynamic presentation & collection. Hypothetically, if you provide a list to check from in the GET method, it can be displayed like so in HTML:
<p><h3>Select Applicable Characteristics:</h3></p>
{% for c in chars %}
<p><h4><input type="checkbox" name="{{ c }}" value="{{ c }}"/> {{ c }}</h4></p>
{% end %}
The POST method can iterate that list, collect for each and create a list input. It's slightly more technical but I could not make the aforementioned solution work.
# Characteristics loop
chars = [x.split('_')[1] for x in bs.attr.keys('chr_*')]
checked_chars = []
for c in chars:
checked = self.get_argument(c, None)
if checked is not None:
checked_chars.append(checked)
This combines Tornado's templating (jinja2) feature with some html for a simple interface. Doable & quick, admittedly not the best production solution. Hope this helps!
精彩评论