【问题标题】:Django filter dropdown Dynamially to remove previously selected valueDjango过滤器下拉列表动态删除以前选择的值
【发布时间】:2020-01-21 06:52:45
【问题描述】:

我有 4 个下拉菜单,它们都是通过 django 模型填充的。因此,假设值是主键,当我在第一个下拉菜单中选择任何值时,它不应该在剩余的下拉菜单中可用。

我已经搜索并尝试了接受的 jquery 答案 Similarly asked question 但它根本不起作用。

这是我的示例代码:

#views.py

from .models import myModel

def myFunction(request):
    data = myModel.objects.all()
    return render(request,'myPage.html',{'myData':data})

#myPage.html
<table>
<div id="select-group">
<tr>
   <td>
    <select name="dd1" id="dd1">
    {% for data in myData %}
       <option value={{data.id}}>{{data.name}}</option>
    {% endfor %}
    </select>
  </td>
  </tr>
<tr>
   <td>
    <select name="dd2" id="dd2">
    {% for data in myData %}
       <option value={{data.id}}>{{data.name}}</option>
    {% endfor %}
    </select>
  </td>
</tr>
... and rest
</div>
</table>
#jQuery
$('#select-group select').change(function(){
    var values = [];
    $('#select-group select').each(function(){
        if(this.value.length > 0)
            values.push(this.value);
    });

   $('#select-group select optgroup').each(function(){
        $(this).after('<option>'+          $(this).attr('label')+'</option>').remove();
    });

    $('#select-group select option').each(function(){   
        if($.inArray(this.value, values) > -1 &&
           !this.selected)                
        $(this).after('<optgroup label="'+this.value+'"></optgroup>').remove();
    });

});​

我错过了什么? jQuery 有什么问题吗?

【问题讨论】:

标签: jquery django filter dropdown


【解决方案1】:

这个 jQuery 完美运行...

$(document).ready(function() {
$('select').on('change', function() {
  var selectedValues = [];
  $('select').each(function() {
    var thisValue = this.value;
    if(thisValue !== '')
      selectedValues.push(thisValue);
  }).each(function() {
    $(this).find('option:not(:selected)').each(function() {
      if( $.inArray( this.value, selectedValues ) === -1 ) {
        $(this).removeAttr('hidden');
      } else {
        if(this.value !== '')
          $(this).attr('hidden', 'hidden');
      }
    });
  });
});
});

【讨论】:

    猜你喜欢
    • 2017-11-07
    • 1970-01-01
    • 2016-02-17
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多