HTML 选择框,从 servlet 中选择数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5298049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Select Box, selected data from servlet
提问by newbie
Good day!
再会!
I am having a problem with the select box in html. I am on the EDIT portion of my simple CRUD project and before users can edit, the chosen data will be shown first and I retrieved it in the database through the servlet.
我在 html 中的选择框有问题。我在我的简单 CRUD 项目的 EDIT 部分,在用户可以编辑之前,将首先显示所选数据,然后我通过 servlet 在数据库中检索它。
Now I want the data I retrieve be the one SELECTED (default) in my select box. ${product.category}
现在我希望我检索的数据是我选择框中的一个 SELECTED (默认)。 ${product.category}
<select size="1" name="category">
<option value ="1">Dogs</option>
<option value ="2">Cats</option>
<option value ="5">Others</option>
</select>
I tried inserting it like this but it doesn't work.
我尝试像这样插入它,但它不起作用。
<select size="1" name="category" selected=${product.category}>
<option value ="1">Dogs</option>
<option value ="2">Cats</option>
<option value ="5">Others</option>
</select>
I want to do something like this.. If (${product.category}==1), selected=option 1...
我想做这样的事情.. 如果 (${product.category}==1), selected=option 1 ...
I've seen something like THISin one of the forums but it is in PHP format. How can I do it using JSP?
我见过像这在论坛中的一个,但它是在PHP格式。我如何使用 JSP 做到这一点?
Thank you very much.
非常感谢。
回答by BalusC
The selected
attribute has to go on the HTML <option>
element and it should onlybe set when the option value matches. Most elegant way is to use the conditional operator ?:
.
该selected
属性必须放在 HTML<option>
元素上,并且只有在选项值匹配时才应该设置它。最优雅的方法是使用条件运算符?:
。
<select name="category">
<option value="1" ${product.category == '1' ? 'selected' : ''}>Dogs</option>
<option value="2" ${product.category == '2' ? 'selected' : ''}>Cats</option>
<option value="5" ${product.category == '5' ? 'selected' : ''}>Others</option>
</select>
Better would be if you have the items in some List
or Map
. E.g. a List<Category>
where Category
has id
and name
properties.
如果您在 someList
或Map
. 例如,一个List<Category>
whereCategory
有id
和name
属性。
<select name="category">
<c:forEach items="${categories}" var="category">
<option value="${category.id}" ${product.category == category.id ? 'selected' : ''}>${category.name}</option>
</c:forEach>
</select>
This way you don't need to repeat the same thing for all options.
这样你就不需要对所有选项重复同样的事情。