Thursday 7 January 2016

Disabling contents of div element in JSP

This post will explain on how to disable the content of div element in a jsp using jquery, based on the session attribute.

In this example, the checkbox present inside the employeediv is disabled, provided the role of the user fetched from the session is admin.

Fetching the session attribute:

Using this code snippet, the session attribute called ROLE is fetched. Based on the type of role, the “isAdmin” flag is set to either true or false.

<%String sRole = (String)request.getSession().getAttribute("ROLE");
boolean isAdmin = false;
if ((sRole.equals("Admin"))|| (sRole.equals("admin"))|| (sRole.equals("ADMIN")))
            isAdmin = true;
%>

Creating a hidden variable:

The isAdmin flag is stored in a hidden variable.

<INPUT type="hidden" id="role" name="role" value="<%=isAdmin%>"/>     

Disabling the DIV element:

Using the script below, onLoad of jsp, the content of the employeediv is disabled if “isAdmin” is set to true.

<script type="text/javascript">
jQuery(document).ready(function ($) {
  var isAdmin = document.getElementById("role").value;
  if($('#isAdmin')){
            $('#employeediv :input').attr('disabled', true);
    }
});
</script>

All the elements inside the “employeediv” will be disabled if the “isAdmin” is set to true.

<div id="employeediv">
<s:form name="testForm" id="testidForm" action="testaction">
<s:checkbox name="empagreement" id="empchk1" />Employee declaration<br/>
<s:checkbox name="empcitizenship" id="empchk2" />Indian<br/>
</s:form>
</div>

No comments:

Post a Comment