问题
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.
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?
回答1:
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>
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.
来源:https://stackoverflow.com/questions/8948629/keep-selected-value-in-an-html-form-after-submit-is-pressed