【问题标题】:Get a listbox's selected items in javascript在javascript中获取列表框的选定项目
【发布时间】:2009-05-13 21:23:58
【问题描述】:

我在 asp.net 中有两个列表框。单击按钮时,我想加载一个列表框,其中包含另一个框中所选项目的元素。问题是这必须在客户端完成,因为单击按钮时我不允许它提交。我想调用一个javascript函数onselectedindexchange,但那是服务器端。有任何想法吗?我应该更清楚吗?

解决方案

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++;
        }
    }
}

【问题讨论】:

  • 您必须像添加到 SELECT 元素一样在 javascript 中添加项目,使用更简单的方法进行更新,因此不需要迭代器行

标签: asp.net javascript vb.net


【解决方案1】:

试试:

 //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));
  }                  

【讨论】:

  • 我试过这个和类似的东西。但是'我得到的对象不支持这个属性或方法'
  • 确保在变量声明之前包含“var”,并且不要将函数命名为与您的 ID 之一相同的名称
  • 尝试在 firefox 中运行代码,如果它在 forefox 中运行,那么这可能是我提到的为什么它在 IE 中无法运行的原因之一
  • 我试过你说的。它没有用。我将您的代码编辑为我拥有的代码,除了最后一行之外,它似乎都喜欢它。 (见编辑过的问题)
  • 我刚刚添加了您想要的列表选项的最终选择,“值或文本”我输入了值。
【解决方案2】:

更准确地说,我们可以这样做;

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

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

【讨论】:

    【解决方案3】:

    这里有一个很好的article,关于如何使用 Jquery 来做到这一点。

    您也可以将下拉菜单粘贴在更新面板中。

    【讨论】:

      【解决方案4】:
      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++;
          }
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        相关资源
        最近更新 更多