JavaScript + Add Items to Dropdown Menu
I have two dropdowns in my JSP page
1. lstA
test1
test2
test3
test4
2. lstB
Now when I select lstA I want to fill all lstA items in lstB except the selected one, also the contents of lstA should remain unchanged.
How can I achieve this?
I tried to do this, but removed some random items from lstA which are reasonably padded.
source to share
you almost got it right in your answer.
what to note: you need to clear the client list before adding, otherwise you will get more and more items on it and you need to clone this setting before adding it to the client list, because a node can only exist in one 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>
source to share
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 both drop-down.
When I do this, some data is accidentally populated in the clientItem and some items from the selectItem are removed.
source to share
try it
<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 is added to the dropdown list.
source to share