Search code examples
htmljsp-tags

Default value to select option menu is not recognized


Below is the code used for simple html and it works:

<select id="name" class="state">
    <option value="Brad" selected="selected">
        Brad
    </option>

    <option value="Carol">
        Carol
    </option>

    <option value="Derrick">
        Derrick
    </option>
</select> 

Is there another method that i can use so that I can set a default value to my select option tag?

In my jsp file:

</html:select>
<html:option value="0">--Select--</html:option>
                    <html:option value="Brad" selected="selected">Brad</html:option>
                    <html:option value="Carol">Carol</html:option>
                </html:select>

The <option value="Brad" selected="selected"> Brad </option> works in simple html. Brad is shown before clicking the dropdown arrow. My problem is that when I used this in my jsp it says that "The attribute is not recognized <html:option value="Brad" selected="selected">Brad</html:option>"


Solution

  • If you are using JSP then there is a tag for html-select-dropdown. Using <form:select> tag you can do something like this -

    <form:select path="country">
       <form:option value="NONE" label="--- Select ---"/>
       <form:options items="${yourList}" />
    </form:select>
    

    To know more about how to use jsp select tag dig deep into this link.

    And for assiging default value take help from this answer.

    Update
    This is how you can include JSTL in you JSP

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
    
    <html>
        <head>
            <title></title>
        </head>
        <body>
    
        </body>
    </html>
    

    Here you see prefix="form", you can name the prefix as you want. You can find more detail here.