0

I currently have in javascript:

var target = getTarget();

I want to check that target does not start with "select" so I am thinking of using the java method startsWith to do that because I couldn't find an equivalent in javascript

So I did:

<%if(!target.startsWith(select)%>
    {
        targetValue = getTargetValue();
    }

I end up getting an error stating:

target cannot be resolved

How can I go by resolving this, from my understanding if I use the <%%> then I can use java code

2 Answers2

0

Java runs on server side, while JavaScript runs on client side. Java code is executed when generating the HTML, while JavaScript will be executed when the generated HTML is downloaded to the client browser and the browser renders the HTML to the end user. In short: Java code cannot access to JavaScript code, nor viceversa1.

Your specific problem: there's no target variable declared in the Java server code (inside scriptlet). You should use plain JavaScript to achieve what you want/need. Here's a piece of code adapted from How to check if a string “StartsWith” another string? (using second most voted answer because it is shorter than the accepted answer):

var target = '';
if (getTargetValue().lastIndexOf('select', 0) === 0) {
    target = getTargetValue();
}

Also, you should avoid writing Java code directly in JSP.


1: You can write the content of Java variables in HTML to assign the data to JavaScript variables, but this can be done only when generating the HTML. If you perform an ajax operation, any Java code won't be re executed, so any scriptlet (that thing inside <% %>) won't be re evaluated.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

target is a JavaScript variable, so when you try to use it to call a Java method, the .jsp pages are going to look for target as a Java variable, not JavaScript. A workaround could just be:

if(target.substring(0, select.length) !== select){}