简体   繁体   中英

Get a listbox's selected items in javascript

I have two listboxes in asp.net. On the click of a button I want to load a list box with the elements of the selected items in the other box. The problem is that this has to be done on the client side because when the button is clicked I don't allow it to submit. I want to call a javascript function onselectedindexchange but that is server side. any ideas? Should i be more clear?

Solution

enter code here
function Updatelist() {
    var sel = document.getElementById('<%=ListBox1.ClientID%>')
    var lst2 = document.getElementById('<%=ListBox2.ClientId %>')
    var listLength = sel.options.length;
    var list2length = lst2.options.length;
    for (var i = 0; i < listLength; i++) {
        if (sel.options[i].selected) {
            //lst2.options.add(sel.options[i].text);
            lst2.options[list2length] = new Option(sel.options[i].text);
            list2length++;
        }
    }
}

Try:

 //onclick for button calls this function
 function Updatelist() {
 var sel = document.getElementbyId("list1");
 var listLength = sel.options.length;
 for(var i=0;i<listLength;i++){
    if(sel.options[i].selected)
    document.getElementById("list2").add(new Option(sel.options[i].value));
  }                  

more precisely we can do it like;

function selectedVal(list) {   
    alert(list.options[list.selectedIndex].text);                  
} 

<select id="listbox" multiple="multiple" 
        style="height: 300px; width: 200px;" 
        onclick="javascript:selectedVal(this);">  
</select>

Here is a good article on how to do this using Jquery.

You could also stick your drop downs in an Update Panel.

function Updatelist() {
var sel = document.getElementById('<%=ListBox1.ClientID%>')
var lst2 = document.getElementById('<%=ListBox2.ClientId %>')
var listLength = sel.options.length;
var list2length = lst2.options.length;
for (var i = 0; i < listLength; i++) {
    if (sel.options[i].selected) {
        //lst2.options.add(sel.options[i].text);
        lst2.options[list2length] = new Option(sel.options[i].text);
        list2length++;
    }
}

}

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