Rani Indrastia Rani Indrastia - 6 months ago 33
Javascript Question

JSP-html button enable-disable condition

I tried some code to make disable-enable button by condition, but it apparently not working as I want:

<form method="get" action="reg.jsp">
<%
if ((String)session.getAttribute("dept") == "HR") {
%>
<th colspan="1"><input type="submit" value="Register"/></th>
<% }
else {
%>
<th colspan="1"><input type="submit" value="Register" disabled></th>
<th><%= session.getAttribute("dept")%></th>
<%
}
%>
</form>


And it works like this:

button-unable

enter image description here

The "register" button supposed to be enable when the "department" is "HR".

Please help me to spot what I missed.. :(

Answer

Do not use Java code in your JSP. Use JSTL tags or JSP Expression language.

How to avoid Java code in JSP files?

Your markup can be much simplified using expression language as below:

<form method="get" action="reg.jsp">
    <th colspan="1">
         <input type="submit" value="Register" ${sessionScope.dept eq 'HR' ? '' : 'disabled' }/>
    </th>  
    <th>
         ${sessionScope.dept}
    </th>
</form>