I am using JQuery to insert HTML in my DIV element
I have the following code in my JSP page
<div id="definitionsDiv">
<s:select id="typeDropdown" list="types" listKey="id" listValue="value" value="3" onchange="getWordList()"/>
</div>
HTML looks like
<div id="definitionsDiv">
<select id="typeDropdown" onchange="getWordList()" name="">
<option value="1">Adverb</option>
<option value="2">Adjective</option>
<option selected="selected" value="3">Noun</option>
<option value="4">Other</option>
</select>
</div>
This works fine and displays a dropdown with the values retrieved from the “types” field in my Struts action.
However, I want to dynamically generate this HTML so I call the following in my doc load method ….
function buildDefinitionsHTML()
{
$("#definitionsDiv").empty();
$("#definitionsDiv").append('<s:select id="typeDropdown" list="types" listKey="id" listValue="value" value="1" onchange="getWordList()"/>');
}
Now my generated HTML looks like
<div id="definitionsDiv">
<s:select id="typeDropdown" onchange="getWordList()" value="1" listvalue="value" listkey="id" list="types"></s:select>
</div>
It seems there has been no call made back to my action to populate the options list as happens when I leave the static HTML in my page. Any ideas how to get this to work?
It’s impossible for client-side JavaScript to add server-side code to a page. What you need to do is create both blocks of HTML server-side and hide one of them.
JSP isn’t my area, but this might work. JSP/HTML:
jQuery:
Using
.append()in this way will move the existing DOM elements from the hidden DIV into the desired target DIV.However, using
display:noneonly hides the second DIV from the page; it doesn’t remove it. Therefore, you may want to movedefinitionsDiv2outside of your<form>tags so it doesn’t get submitted invisibly along withdefinitionsDiv.