How to trigger the Javascript/AJAX code when the value of my dropdown changes?

curiousIT :

I have a Django project where I'm trying to run a JS/AJAX script when a dropdown changes value. The same code works well for a button, but not for the dropdown.

Here is the html code with the button, the dropdown and finally the script:

  <button class="toChange">AJAX POST TEST</button>

  <select class="toChange">
    {% for item in regions %}
    <option val="{{ item }}" {% ifequal item reg %} selected {% endifequal %}> {{ item }} </option>    
    {% endfor %}
  </select>

  <script type="text/javascript">
       $(".toChange").click(function(){
        $.ajax({
            type: 'POST', 
        }); 
    });

EDIT1: adding views.py and amending my dropdown to reflect it properly as I might have oversimplified my example.

def MyView(request):
    result_r = request.POST.get('reg')

    if request.method == 'POST' and request.is_ajax:

        result_r = request.POST.get('reg')
        query_results = data_immo.objects.all()
        regions = data_immo.objects.values_list("nom_reg", flat=True).distinct().order_by('nom_reg')
        departements = data_immo.objects.values_list("insee_dep").filter(Q(nom_reg=result_r)).distinct()

        query_results_dict = {
        'query_results': query_results,
        'regions': regions,
        'departements': departements,
        'reg': result_r
        }

        return render(request,'home.html', query_results_dict)

Why would it work with the button and not the dropdown? I'm really new to this, so do idea what is wrong. Thanks!

Anurag Srivastava :

You need to use the change event in case of <select>

$(".toChange").on('change', function(){ ... })

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31890&siteId=1