按下提交后,将选定的值保存为html表单 [英] keep selected value in an html form, after submit is pressed

查看:167
本文介绍了按下提交后,将选定的值保存为html表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,有几个选择选项。举例说明:

I have a simple form with a couple of select options. To illustrate it:

<form action="" method=GET>
    <select name="sort">
        <option value="name">name
        <option value="age">age
        <option value="gender">gender
        <option value="location">location
    </select>
    <input type="submit" value="sort">
</form>

假设用户使用表单,选择性别并点击提交按钮。

Say that the user uses the form, selects gender and hits the submit button.

我根据用户输入对记录进行排序(顺便说一句,在Django中),然后渲染相同的页面,但按照用户需要排序。

I sort the records based on user input ( in Django by the way ) and then I render the same page, but sorted as the user wanted.

我的问题:我可以以某种方式保留选定值的性别而不是名称,这是第一个吗?

My question: can I, somehow, keep in the form the selected value gender and not name, which is the first one?

推荐答案

将当前排序字段传递回模板,然后根据选项文档将该选项标记为 selected
https://developer.mozilla.org/zh/HTML/Element/option

Pass the current sort field back to the template, then mark that option as selected as per the option docs: https://developer.mozilla.org/en/HTML/Element/option

<option value="name" {% if sort == 'name' %}selected{% endif %}>name</option>
<option value="age" {% if sort == 'age' %}selected{% endif %}>age</option>
<option value="gender" {% if sort == 'gender' %}selected{% endif %}>gender</option>
<option value="location" {% if sort == 'location' %}selected{% endif %}>location</option>

如果您使用了django表单框架,这样做会更容易。

This would all be easier if you used the django forms framework.

class SortForm(forms.Form):
    sort = forms.ChoiceField(choices=[(x, x) for x in ['name', 'age', 'gender', 'location']])

def myview(request):
    form = SortForm(request.GET or None)
    # apply sort
    return render(request, "mytemplate.html", {'form': form})

{{ form.as_p }} # this would auto select whatever the form is bound with.

这篇关于按下提交后,将选定的值保存为html表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆