Reputation: 189
I have a button which opens a popup window and lets me to choose something from a list and then returns to parent page with the ID and NAME variables. In the parent page, I store ID in an hidden field and NAME in a textbox. This is ok when i choose one thing from list. But now I want to choose multiple things and store ID's and NAME's in a listbox value and text property. How can I do that? These are the javascript codes I am using for textbox and hidden field.
<script type="text/javascript">
function get_selected_machine(ID, NAME) {
document.getElementById("txtName").value = NAME;
document.getElementById("hdnID").value = ID;
}
</script>
Upvotes: 2
Views: 1981
Reputation: 1136
It is very easy. You can use following function-
function selectCompany(text, value)
{
var opt = document.createElement("option");
document.getElementById('<% =listBoxId.ClientID %>').options.add(opt);
opt.text = text;
opt.value = value;
}
I hope this would have helped you.
Upvotes: 0
Reputation: 61832
Below is a very simple example that illustrates how to get the values from a listbox using pure JavaScript. How you decide to store the values on the client once you have them is up to you.
HTML:
<select id="multiSelect" size="5" multiple="multiple">
<option value="o1">Option 1</option>
<option value="o2">Option 2</option>
<option value="o3">Option 3</option>
<option value="o4">Option 4</option>
<option value="o5">Option 5</option>
<option value="o6">Option 6</option>
</select>
<br />
<button id="btnGetValues" onclick="GetValues()">Get Values</button>
JavaScript
function GetValues() {
//Get select object
var myList = document.getElementById("multiSelect");
//Create array to store selected values
var aryMySelectOptions = new Array();
//Loop through all values and grab selected
for (var i = 0; i < myList.options.length; i++) {
if (myList.options[i].selected) {
aryMySelectOptions.push(new selectOption(myList.options[i].innerText, myList.options[i].value));
}
}
//Loop through selected values and alert for debugging purposes
for (var i = 0; i < aryMySelectOptions.length; i++) {
alert("Text: " + aryMySelectOptions[i].text + ". Value: " + aryMySelectOptions[i].value + ".");
}
}
function selectOption(text, value) {
var text;
var value;
this.text = text;
this.value = value;
}
Here's a working jsFiddle.
Note: The jsFiddle uses jQuery, but only as a means of attaching to the click event of the button. I did not use jQuery for anything else because I'm assuming that you want a pure JS solutions (you didn't tag jQuery in your post).
Upvotes: 2