Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Select Box, selected data from servlet

Tags:

html

select

jsp

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.

Now I want the data I retrieve be the one SELECTED (default) in my select box. ${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...

I've seen something like THIS in one of the forums but it is in PHP format. How can I do it using JSP?

Thank you very much.

like image 890
newbie Avatar asked Mar 14 '11 11:03

newbie


1 Answers

The selected attribute has to go on the HTML <option> element and it should only be set when the option value matches. 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>

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.

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

like image 173
BalusC Avatar answered Nov 16 '22 12:11

BalusC