sending checkbox array from js to django views

后端 未结 1 1655
南方客
南方客 2021-01-17 03:03

I\'m confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array

javasc

相关标签:
1条回答
  • 2021-01-17 04:00

    For getting the selected checkbox values and sending as an array using ajax you can use jquery like this:

    consider you have multiple checkboxes and a button.

    <input type="checkbox" name="imageName">
    <input type="checkbox" name="imageName">
    .......
    <button id="deletePhoto">Delete</button>
    

    after selecting multiple checkbox values click on this button. On clicking the below jquery will be triggered to make an arrya of selected checkbox values.

    //jquery for getting the selelcted checkbox values 
    
      $(document).on("click","#deletePhoto",function(){
    
        var favorite = [];//define array
    
        $.each($("input[name='imageName']:checked"), function(){            
            favorite.push($(this).val());
        });
    
        alert("Photo Selected: " + favorite.join(", "));
    
        if(favorite.length == 0){
          alert("Select Photo to delete");
          return false;
        }
    
        //ajax for deleting the multiple selelcted photos
        $.ajax({type: "GET",
        url: "/olx/deletePhotoFromEdit",
        data:{
          favorite:favorite
        },
        success: function(){
         // put more stuff here as per your requirement
        });
    
       }
        });
    
    });
    

    In the view you can get the array like this:

    selected_photo = request.GET.getlist('favorite[]')
    
    0 讨论(0)
提交回复
热议问题