umair
umair

Reputation: 99

how to put JavaScript code in a java String variable

I have a javascript code. Eg:

<script type="text/javascript">
AJS.$("#customfield_10306 option[value='-1']").remove();

(function($)
{
new AJS.MultiSelect(
{
element: $("#customfield_10306"), itemAttrDisplayed: "label", errorMessage: AJS.params.multiselectComponentsError
});
}
)(AJS.$);
</script>

I would like to put this in a java String type. So,

String someCode = above java script code

What is a quick and nice way of doing this rather than putting all the JS code in one line in quotes and using \ everywhere.

Thanks.

Upvotes: 0

Views: 1406

Answers (3)

Rais Alam
Rais Alam

Reputation: 7016

You can do apply some logic here

  1. Put all your JavaScript code in a file
  2. Read the file in Java code with the help of IO and put them to a string

Now your string is full of JavaScript written in file. If you will do so then your code will will be dynamic and you can change Javascript code any time. No java compilation will be required.

Upvotes: 0

mdo
mdo

Reputation: 7111

Simply use a multiline literal like this:

String s = "first line\n"
         + "second line";

As the strings are known at compile time the string will be concatenated then. No need to use a StringBuffer at runtime with constant strings.

Upvotes: 0

SpringLearner
SpringLearner

Reputation: 13854

use stringbuffer then use append()

For example

    StringBuffer buffer=new StringBuffer("<script type="text/javascript">");
buffer.append("AJS.$("#customfield_10306 option[value='-1']").remove();");

Upvotes: 1

Related Questions