Reputation: 425
I'm currently implementing a website using HTML/CSS, JSP/Servlet, and Javascript. JSP controls which part of the page should be generated depending on a session value (for example, depending on whether a user is currently logged in or not), and Javascript has some actions on the elements of the generated document (e.g., div sections).
But I'm having an issue of using document div id values from Javascript when the div section is not generated because of the condition in the JSP code.
For example a page has two sections, where only one of the sections will be generated from JSP depending on the session value condition. And there is a Javascript file that has a set of functions to apply to each section using the 'id' of the div tag or its sub-tags. But since JSP does not generate all the sections, some of the 'id' used by the Javascript does not exist in the returned HTTP request. Below code snippets show an example. JSP file is as below.
<script src="script.js"></script>
...
<%
if(some condition) {
%>
<div id="someID"></div>
And as below, script.js has some function applied to the 'someID' to emit some html and apply actions on it. But someID would not exist if the JSP condition is not satisfied, producing a Javascript error for using unidentified id.
$function() {
$('#someID').html( ..... )
}
The question is rather verbose, but simply stated, "I'd like to conditionally generate some section of HTML from JSP, and apply some actions on the generated sections using Javascript. But the id of div section that is not generated from JSP because of the condition is used by the Javascript, which generates an error. How could I design this?"
Thanks.
Upvotes: 0
Views: 734
Reputation: 1249
You can simply check
if($('#someID')) {
.. do this..
}
or
if(document.getElementById('someId')){
..do this...
}
Upvotes: 1
Reputation: 2245
You can simply check if element exists via javascript to avoid errors:
if($('#someID').length > 0)) {
$('#someID').html( ..... )
}
Upvotes: 1