简体   繁体   中英

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.

<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");
}

You can try this uisng jQuery

function addListFunction() {

var optionList = [{"key":"1" , "value":"item1"},
                  {"key":"2" , "value":"item2"},
                  {"key":"3" , "value":"item3"},
                  {"key":"4" , "value":"item4"},
                  {"key":"5" , "value":"item5"},
                  {"key":"6" , "value":"item6"}];

var combo = $("<select>").attr("id", "inputAuto").attr("name", "selectTag");

$.each(optionList, function (j, el1) {
                var opt = $("<option>").attr("value",el1.key).append(el1.value);
                combo.append(opt);
         });

$("#DivId").append(combo);
}

In this i have statically define the array of option (eg optionList). But you can make an ajax call for this.

The struts tags are only interpretet once by the server before the page is delivered. If you manipulate the dom afterwards with JavaScript you can't use JSP Tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM