Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

using jstl tags in javascript  RSS feed

 
sreenath bhasker
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my servlet code i have set the attribute
request.setAttribute("intances", instances);

now in my jsp ,i have a javascript function on body load,
here i need to check whether "instances" attribute is null or not.

function test(){
if('${instances}'!=null){
alert('no null');
}

doesn't work
 
sreenath bhasker
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got the answer,
'${"instances"}'
if you print this out using javascript alert you'll find object stored in the attribute
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Javascript occurs on the client after the JSP is already finished, so it can't be reactive to javascript actions.

That being said, the ${instances} output will be translated to a String when used in that context, and the String will be available for the javascript comparison.

If instances IS null, it would print an empty string, not "null" and not a javascript null object. So the javascript would look like:
if(''!=null)
Which would never be true. An empty String is not a null object - even in javascript.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sreenath bhasker:
got the answer,
'${"instances"}'
if you print this out using javascript alert you'll find object stored in the attribute


Are you sure that is doing what you expect it to? Look at the HTML code generated by the JSP in your browser. I would expect the output from that to be:
if('instances' != null)
no matter what value is actually stored in the instances variable on the server (null or not) because you aren't outputting the variable instances, you are outputting the String "instances".
 
Jeremy Wischusen
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
have you tried
var instances = <cut value="${instances}"/>
if(instances!=''){
alert('no null');
}
There at least you have a javascript variable to reference and you are not relying on there being a value in the JSP variable for the conditional check.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!