HTML Select Box, selected data from a servlet

Good day!

I have a problem with a select box in html. I am in the EDIT part of my simple CRUD project and before users can edit, the selected data will be shown first and I will extract it to the database through the servlet.

Now I want the data I receive to be selected in the SELECTED select box (default). ${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 to insert it like this, but it does not 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 ...

I saw something like this on one of the forums, but in PHP format. How can I do this using JSP?

Many thanks.

+8
html select jsp
source share
1 answer

The selected attribute should be included in the HTML <option> element, and with the value of the parameter, it should only . The most elegant way is to use the conditional operator ?: .

 <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> 

It will be better if you have items in some List or Map . For example. a List<Category> , where Category has id and name properties.

 <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 do not need to repeat the same thing for all parameters.

+11
source share

All Articles