2014-02-25 64 views
0

我有一个Django表单。其中一个字段(monitoring_method)使用自动完成灯光部件,根据另一个字段(database_type)中的条目过滤结果。在提交之前,有没有办法在database_type字段中获取用户输入的值?我会知道如何用AJAX做到这一点(或者可以搞清楚),但我不确定 - 也许这是我真正的问题 - 如何将AJAX与自动完成相结合。在提交之前获取表单字段的值

class MonitoringMethodAutocomplete(autocomplete_light.AutocompleteBase): 
    autocomplete_js_attributes = {'placeholder': 'Choose a database type to enable monitoring method selection'} 

    def choices_for_request(self): 
     q = self.request.GET.get('q', '') 
     db_type = self.request.POST.get('database_type') 
     # if not db_type: 
     #  return [] 
     monitoring_methods = Database.objects.values_list('monitoring_method', flat=True) 
     return monitoring_methods.filter(database_type__exact=db_type, 
             name__icontains=q).distinct() 
    def choices_for_values(self): 
     return [] 

编辑: 所以,我本来想出什么我试图做是不可能的,但后来我意识到,q变量在做类似的事情...那么,为什么不db_type工作?

回答

0

耶。

<script type="text/javascript"> 
$(init); 

function init() { 
    var database_form = $('.asset-form'); 
    var db_type_field = $('#id_database_type'); 
    database_form.data('db_type', db_type_field.val()); 

    db_type_field.on('change', function() { 
    var db_type = db_type_field.val(); 
    console.log(db_type); 
    $('.autocomplete-light-text-widget').yourlabsAutocomplete().data = {'database_type':db_type}; 
    }); 

    // disable enter key from posting form 
    $('#id_database_type').keypress(function(event) { 
     if (event.which == 13) { 
      event.preventDefault(); 
     }; 
    }); 
} 

</script> 
相关问题