Sujal Sujal - 1 month ago 12
Javascript Question

Add Struts 2 select drop down list dynamically using JavaScript/JQuery

I have a

student.jsp
page that loads a select drop down list from the database Faculty

<s:select list="ftyList" name="fid" listKey="fid" listValue="name" label="Select a Faculty" />


Now, I've got to add more of the exact same drop down list when I click on Add button. For that I've got a
div
with Add button and my JavaScript code as below:

<div id="div">
<button onclick="addListFunction()">Add</button>
</div>


addDropDown.js:

function addListFunction() {
var d = document.getElementById("div");
d.innerHTML += "<p><s:select list='ftyList' name='fid' listKey='fid' listValue='name' label='Select a Faculty' /></p>";
}


The problem is that when I click on the 'Add' button it's only adding an empty space. When used firebug, I could see the Struts tag was being printed the same as above instead of HTML tags.

Answer

<s:select> is a struts tag which cannot be added directly from javascript and assumed to run server side.

You can use jQuery Clone method when Add button is clicked.

<s:select list="ftyList" name="fid" listKey="fid" listValue="name" cssClass="fidSelect" label="Select a Faculty" />

function addListFunction() {    
    $('.fidSelect').clone().insertAfter(".fidSelect");
}
Comments