aloplop85
aloplop85

Reputation: 922

Create Struts2 tag inside JavaScript function

I would like to know if it is possible to create a Struts2 tag (e.g. ) inside a JavaScript function or using jQuery.

For instance, I tried:

function createStrutsTag(){           

        var newElement;
        newElement= document.createElement("div");
        newElement.className = 'newer';
        newElement.innerHTML = '<s\:textfield label="HELLO" \/>';              

        newElement.css('visibility','visible'); }

However, it just created the div containing the label < s:textfield label="HELLO" /> without being parsed to its real meaning.

I also tried with struts2-jquery-plugin tags (sj) which also crashed...so I would like to know if it can be done or I should create those elements in the HTML part of the body, being hidden by CSS style and then show or hide them using JavaScript /jquery functions as they are needed by the application.

Upvotes: 0

Views: 3158

Answers (1)

Dave Newton
Dave Newton

Reputation: 160181

JS is executed on the client. JSP tags are evaluated on the server.

You have several options, not limited to:

Use the output of the text tag as a JS value

There are at least two ways to do this:

  • Put the JS in a JSP, or
  • Evaluate your JS via the JSP processor

Evaluate some JS in the JSP and call the external JS

For example, you could create a hash of I18N labels etc. in your JSP and pass it to JS functionality that lives in a JS file (where it should live).

Store the output of the text tag in a hidden DOM element

Retrieve it using JS and construct your DOM as you are now.

This is arguably the cleanest.


Rough overview of "clean" solution using jQuery

See this fiddle for the basics.

JSP:

<div id="hello" style="display: none;"><s:text label="HELLO" /></div>

JS:

function createDiv() {
  var $div = $("<div className='newer'>").html($("#hello").html());
  $("#outputHere").html($div);
}

It could be tightened up a bit, but that's the general idea.

Upvotes: 2

Related Questions