Search code examples
jqueryhtmljspstruts-1

How to change HTML option tag color programmatically?


I want to make blue the item with CODE != "abc012345" in the select combo "#accountSelector";

I tried the following solution and it works correctly but there's code replication (the content of the "option" tag is replicated into IF ELSE statements).

How can I change the color of the option tag in order to avoid code replication? Is there any javascript/jquery cleaner solution?

<table border="0" cellPadding="0" cellSpacing="0" >
    <logic:notEmpty name="enabledReportsList" >
        <tr>
            <td>
            <select id="accountSelector" name="accountSelector" style="WIDTH: 380px" class="comboFilter" onChange="preSubmit();document.changeReports.submit()">                
                    <logic:iterate id="cc" indexId="ccn" name="enabledReportsList" >        
                     <% if (!( ((it.myproject.common.Report)cc).getCode() ).equals("abc012345")){%>             
                        <option style="color:blue" value="<bean:write name="cc" property="Report"/>" <%= ( ((it.myproject.common.Report)cc).getReport() ).equals(session.getAttribute("accountSelector")) ? "selected" : "" %> >
                            <bean:write name="cc" property="fullValue"/>
                        </option>
                      <%} else {%>
                      <option value="<bean:write name="cc" property="Report"/>" <%= ( ((it.myproject.common.Report)cc).getReport() ).equals(session.getAttribute("accountSelector")) ? "selected" : "" %>>
                            <bean:write name="cc" property="fullValue"/>
                        </option>
                       <%}%>
                    </logic:iterate>
            </select>                   
            </td> 
            <td class="filterheader">
                <b><bean:message key="selector.account" arg0="${fn:length(enabledReportsList)}"/></b>
            </td>
        </tr>
    </logic:notEmpty>

    <logic:empty name="enabledReportsList" >
       <tr>
          <td class="filterheader">
           <bean:message key="ENABLED_REPORTS.combo.empty"/>
          </td>
       </tr>
    </logic:empty>

</table>


Solution

  • It's pretty simple:

    1. Calculate the value of the style in a Java code block without any output:

       <% 
       String style = "";
       if( ... ) {
           style = "style='color:blue' ";
       }
       %>
      
    2. Use the variable:

      <option <%=style%>value="...
      

    Note that you're responsible for properly escaping the content of the variable. In the Java code generated by the JSP compiler, you will get:

     out.write("<option ");
     out.write(style);
    

    i.e. the string will be passed to the client as is.