2013-10-15 227 views
1

我有两个select boxJquery Mobile与相同的数据选项。在当我初始化页面开始我建立他们动态:从其他选择框中选择框中选择框动态删除选项,

var first = document.getElementById("selectBoxFirst"); 
    var second = document.getElementById("selectBoxSecond"); 

    for (var i = 0; i < this.data.length; i++) 
    { 
     first.options[i] = new Option(this.data[i].option, this.data[i].optionId); 
     second.options[i] = new Option(this.data[i].option, this.data[i].optionID); 
    } 

我尝试做的下一件事:当用户选择一个选择框的选项,该选项将在第二个被删除.. 如果你再次选择不同的选项,所以这最后一个选项将从第二个删除和previos将显示,等等...

任何想法如何实现它?

+0

这是你想要的吗? http://jsfiddle.net/Palestinian/bH2we/在这个演示中,您可以一次删除一个选项。 – Omar

+0

@Omar谢谢你的例子,但是选择一个选项不会在第二个复选框中删除这个选项。我寻找类似的东西:[jsfiddle.net/igtr/vHxhx] - 唯一的问题是,在checkBox1中选择项目后,您会得到第二个n-1选项,然后在checkBox2中再次选择将导致n-2在第一个复选框 – Dima

+0

抱歉,我的演示中有一个错误。所以你想要一次选择一个选项,不能同时选择多个选项? – Omar

回答

0

您可以选择隐藏或禁用所选选项。

  1. 隐藏选定的选项(这可能不是旧的浏览器工作)

    • CSS:

      .hide { 
          display: none; 
      } 
      
    • JS

      $('#first').on('change', function() { 
          $('select option.hide').removeClass('hide'); 
          var sel = $('option:selected', this).index(); 
          $('#second option:eq("' + sel + '")').addClass('hide'); 
      }); 
      
      $('#second').on('change', function() { 
          $('select option.hide').removeClass('hide'); 
          var sel = $('option:selected', this).index(); 
          $('#first option:eq("' + sel + '")').addClass('hide'); 
      }); 
      

Demo


  1. 禁用所选的选项:(这并不适用于IE7和更早版本的工作)

    • JS

      $('#first').on('change', function() { 
          $('select option:disabled').prop('disabled', false); 
          var sel = $('option:selected', this).index(); 
          $('#second option:eq("' + sel + '")').prop('disabled', true); 
      }); 
      
      $('#second').on('change', function() { 
          $('select option:disabled').prop('disabled', false); 
          var sel = $('option:selected', this).index(); 
          $('#first option:eq("' + sel + '")').prop('disabled', true); 
      }); 
      

Demo

0

使用普通的JavaScript的方法是相当简单:

var select1 = document.getElementById('first'), 
    select2 = document.getElementById('second'); 

select1.addEventListener('change', function() { 
    while (select2.firstChild) { 
     select2.removeChild(select2.firstChild); 
    } 
    for (var i = 0, len = this.options.length; i < len; i++) { 
     if (this.options[i].value !== this.value) { 
      select2.appendChild(this.options[i].cloneNode()); 
     } 
    } 
}, false); 

DEMO:http://jsfiddle.net/Tp2z7/


你可以写同样使用jQuery短一点:

$('#first').on('change', function() { 
    $('option:not(:selected)', this).clone().appendTo($('#second').empty()); 
}); 

DEMO:http://jsfiddle.net/Tp2z7/1/

+0

试过[jsfiddle](http://jsfiddle.net/Tp2z7/)的例子 - 它不是 在第一个选择框中选择选项后第二个为空 在第二个选择框中选择不会更改第一个选择框中的选项 – Dima

+0

@Dima您使用的是什么浏览器?第一种方法在所有现代浏览器中都可以正常工作。尝试jQuery方法,也许它会对你更好。 – VisioN

+0

@VisionN jQuery示例工作正常!我使用Chrome(11版)。不幸的是,我的项目与jQuery 1.6.4协同工作,'.on'事件在那里不存在。我该如何更换它? – Dima

相关问题