Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set default selected value in Struts2 <s:select> tag?

I am new in Struts2. I have user form, role column have a drop-down list. When user form is in edit mode, the stored values are placed into corresponding controls. But I can't set drop-down list by default selected value. How can I do it?

like image 908
Ganesamoorthy Avatar asked Sep 20 '10 00:09

Ganesamoorthy


3 Answers

In addition to Nate's answer, I've found that I need to put apostrophes around the data in the value attribute if the key type is a String in order for it to recognize that my input value is a String.

like image 107
Robyn P Avatar answered Jan 03 '23 17:01

Robyn P


If the value in your select tag matches a key from the list in the select tag, Struts will do the correct thing and make that value the default. Note that the types must match.

https://struts.apache.org/tag-developers/select-tag.html

like image 24
Nate Avatar answered Jan 03 '23 19:01

Nate


To illustrate this in an example :

<s:select name="employee.course.courseId" value="3"  label="%{getText('label.courseName')}" list="courses" listKey="courseId" listValue="courseName" />
  • Here the Employee object contains an object called "course" and it has a property "courseId"
  • listKey is selected as courseId and the listValue is selected as courseName
  • Hence the output will be like :

        <option value="1">Computer Science</option>
        <option value="2">Electronics</option>
        <option value="3">Mechanical</option>
    
  • The value attribute is set to "3" and it matches the 3rd attribute in the list, which is Mechanical

  • Therefore this will be the default selected value in the dropdown, hence the output html will be like :

        <option value="1">Computer Science</option>
        <option value="2">Electronics</option>
        <option value="3" selected="selected">Mechanical</option>
    

Hope this helps.

like image 35
tharindu_DG Avatar answered Jan 03 '23 17:01

tharindu_DG