Search code examples
jquerydjangofilterdropdown

Django filter dropdown Dynamially to remove previously selected value


I have 4 dropdown menu and all of them are populated through a django model. So, let's say values are primary key and when I select any value in the first dropdown, it should not be available in the remaining dropdown menu.

I already searched and tried the accepted jquery answer from Similarly asked question but it doesn't work at all.

Here is my sample code:

#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();
    });

});​

What am I missing ? is something wrong in the jQuery ?


Solution

  • This jQuery works perfectly...

    $(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');
          }
        });
      });
    });
    });