ilyas Jumadurdyew
ilyas Jumadurdyew

Reputation: 930

Call function on select option change

Niw I have a code, that changes the foreign key according to input method, and request data according to the foreign key, it's all looks like this:

HTML page:

<div class="large-6 columns">
    {% csrf_token %}
    <input  type="text" id="search" name="search" >
    <select id="search-results">
    </select>
</div>

Then the script:

    $(function(){

    $('#search').keyup(function() {

        $.ajax({
            type: "POST",
            url: "/automobile/search/",
            data: {
                'search_text' : $('#search').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

As you can understand on every keyup javascript run this function and loads my html search document which looks like this, into . Here's this html page:

<div>

search_test: {{ val }}

{% for model in models %}
    <option value="{{ model.id }}">{{ modelaname }} ({{ model.automobile_set.count }})</option>
{% endfor %}
</div>

... And now comes question.... How to call function on every select option change according to the select option values, instead of input keyup. Like this:

<select id=search>
<option value="1">Sel1</option>
<option value="2">Sel2</option>
</select>

Upvotes: 2

Views: 2472

Answers (2)

Anurag Deokar
Anurag Deokar

Reputation: 849

you can use change event in drop down. when you change drop-down value, change event is call

$(function(){    
    $('#search-results').change(function() {    
        $.ajax({
            type: "POST",
            url: "/automobile/search/",
            data: {
                'search_text' : $(this).val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });    
    });    
});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
} 

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use change() event handler instead of keyup() handler

$(function(){    
    $('#search').change(function() {    
        $.ajax({
            type: "POST",
            url: "/automobile/search/",
            data: {
                'search_text' : $(this).val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });    
    });    
});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

Upvotes: 2

Related Questions