JavaScript + Adding items into dropdown
I have two dropdowns in my JSP page
1开发者_StackOverflow. lstA
test1
test2
test3
test4
2. lstB
Now on selection of lstA, I want to populate all the items of lstA into lstB except the select one, also the content of lstA should remain the same.
How can I achieve this?
I tried to do it, but from lstA some random items get removed, which is quite wired.
you almost had it correct in your answer there.
things to note : you need to clear the client list before adding, otherwise you'll end up with more and more items on it, and you need to clone the option before adding it to the client list, because a node can only exist in 1 parent at any time.
this has been tested and works for me :
<html><body>
<script language="javascript">
function populateClient() {
var serverList = document.getElementById("dropdown1");
var clientList = document.getElementById("dropdown2");
clientList.options.length = 0; // this removes existing options
for (var i = 0; i <= serverList.options.length; i++) {
if (!serverList.options[i].selected) {
clientList.options.add(serverList.options[i].cloneNode(true)); // cloneNode here
}
}
}
</script>
<select id="dropdown1" onchange="populateClient()">
<option value="value1">value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
<option value="value5">value5</option>
</select>
<select id="dropdown2">
</select>
</body></html>
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
function populateClient(selectItem, clientItem) {
var serverList = selectItem;
for(var i = 1; i <= serverList.options.length; i++) {
if (!serverList.options[i].selected)
clientItem.options.add(serverList.options[i]);
}
}
Where selectItem and clientItem are drop downs.
When I do this, some data is randomly populated into clientItem and some items from selectItem are removed.
精彩评论