10 Aug 2013

Selecting checkboxes in jquery

In my recent side project (clone of imdb.com), number of checkbox options were provided from which user can select the genre(s) of the movie and on the basis of that movies are filtered and shown.
Basically this is divided into two parts, first in which i'll get the all checked genre(s) and second part is to show movie(s) based on that genre(s).




In this post i'm wrting about how i accomplished first part which is divided into number of tasks.

In my template , following is code for showing genre(s) each having  checkbox option.

<div class="refine_box">
        {% for k, v in genre_dic.items  %}
            <input type="checkbox" class="check_id" name="genre" value="{{ k }}">{{ k }} ({{ v }})<br>
        {% endfor %}
</div>

genre_dic is a dictionary having key as a genre and value is number of movies for that genre.

task1: get the value of checkbox which is checked. 
 $(".refine_box input[type=checkbox]").click(function() { 
        
            var isChecked = $(this).is(':checked');
            if(isChecked){
                    alert(#(this).val())
            }
});


task2: get the values of all checkboxes which are checked.
 $(".refine_box input[type=checkbox]").click(function() { 
        
        var arr_refine = [];    //this will store all clicked checkboxes

        $(".check_id:checked").each(function() {
                arr_refine.push(this.value);

        });
 
  }); 

task3: passing array from ajax request to Django view.
In previous task i have created a array holding all genre, so in this task that array we will send to view.
      $.ajax({
                    url: "{% url ajax_refine_movieslist %}",
                    data: {arr_refine: arr_refine},
                   
            });    


Follwoing is whole code of jquery :
 $(".refine_box input[type=checkbox]").click(function() { 
        
        var arr_refine = [];

        $(".check_id:checked").each(function() {
                arr_refine.push(this.value);
               
        });

        $.ajax({
                    url: "{% url ajax_refine_movieslist %}",
                    data: {arr_refine: arr_refine},
                    dataType:'html',
                    success: function(newData){
                         $('.movie_listing').html(newData);
                    }
                   
            });       
   
    }); 
   
task4 : printing the list holding the selected genre(s)
def ajax_refine_movies(request):
    genre_list = request.GET.getlist('arr_refine[]')
    print genre_list


This is how i'm getting the all checkbox selected options.
Soon i'll post second part of this.



No comments:

Post a Comment