2012-09-27 81 views
1

除了我的MVC3项目,我们还分别设计了一个包含3个安全问题和答案的页面(下拉列表中大约有10个)。问题可以从下拉列表中选择,答案将填入下方的文本框中。根据之前的下拉列表更新下拉列表

设计: 让我们说,如果用户选择question1作为(1的10)个问题。第二次下拉应该只显示9个问题(跳过第一个问题)。第三个问题同样只有8个选项。

以同样的方式,如果用户将索引更改为0(说选择问题)。他删除的这个问题应该出现在其他下拉列表中。

请帮助设计此页面。我尝试使用JQuery,这并没有帮助我。

回答

3

试试这个代码

$(function() { 
    // Load all the dropdowns 
    $('[id^=select]').html($('.template').html()); 
    // This array Holds the Objects 
    var arr = ['select1', 'select2', 'select3']; 
    // Declare a array where you store the selections 
    var arrSelect = { 
     'select1': '0', 
     'select2': '0', 
     'select3': '0' 
    }; 

    $('select').on('change', function() { 
     var currID = $(this).prop('id'); 
     // Set the Current selection 
     arrSelect[currID] = $(this).val(); 
     // Iterate Thru each dropdown 
     $.each(arr, function(i) { 
      var temp = arrSelect[arr[i]]; 
      // Clone the template 
      var $clone = $('.template').clone(); 
      // Remove Questions from template based on selected 
      // values in other select's 
      $.each(arrSelect, function(index, value) { 
       if (value != 0 && value != temp) { 
        $clone.find('option[value=' + value + ']').remove(); 
       } 
      }); 
      // If not Current select rewrite its 
      // contents of the select 
      if (arr[i] != currID) { 
       //console.log('#' + arr[i] + ' :: ' + $clone.html()); 
       $('#' + arr[i]).html('').html($clone.html()); 
       $('#' + arr[i]).val(temp); 
      } 
     }); 
    }); 
})​ 

WORKING DEMO

+0

非常感谢你,那很完美。 – Bob

+0

欢迎您:) –

+0

知道这是一个古老的答案,但非常感谢。帮助我太多了! – TheFallenOne

2

我会使用Knockout。基本上创建一个返回可用问题的JavaScript Viewmodel。

我有一个similar requirement和以下工作。

http://jsfiddle.net/mbest/wfW97/

下面是引用代码:

function ViewModel() { 
    var self = this; 
    self.colors = ['red','orange','yellow','green','blue','indigo','violet']; 
    self.selections = []; 
    ko.utils.arrayForEach(self.colors, function() { 
     self.selections.push(ko.observable()); 
    }); 
    self.selfAndUnselectedColors = function(index) { 
     var selfColor = self.selections[index](); 
     return ko.utils.arrayFilter(self.colors, function(color) { 
      return color === selfColor || !ko.utils.arrayFirst(self.selections, function(sel) { 
       return color === sel(); 
      }); 
     }); 
    } 
} 

ko.applyBindings(new ViewModel()); 

和HTML:

<div data-bind="repeat: colors.length"> 
    <select data-bind="options: selfAndUnselectedColors($index), optionsCaption: 'select a color', value: selections[$index]"></select> 
</div>​ 
+0

感谢您的回复以及提供测试的链接。非常感谢。但是我对Knockout没有太多的知识,所以我只使用了sushanthreddy提供的JQuery脚本。 – Bob

+0

没问题。各自为政。当屏幕视图与各种依赖关系复杂时,我倾向于使用Knockout。 – GraemeMiller