简体   繁体   中英

How to check the checkbox field checked and fetch the attribute id value from the element in jquery and django

I have a list of products displayed in a page, and had a checkbox before each and every product record as below

<script>
      $(document).ready(function(){
            $( "#process_button" ).click(function() {
                var hello = $('.css-checkbox_latest')
                console.log(hello);

                $('.css-checkbox_latest').each(function(index){
                  console.log(index);
                });

            });

           });

    </script>


<table>
 {% for product in list_of_products%} 
  <tr>
    <td>
       <input id="{{product.id}}" class="css-checkbox_latest" type="checkbox" />   
    </td>
    <td>
       {{product.name}}
    </td>
    <td>
       {{product.price}}
    </td>
  </tr>
 {% endfor %}
</table>

<input id="process_button" name="" type="button" class="btn btn-large addp_btn"  value="Process">

And had a button as above,

1. so when i clicked on the `button`, i should check whether any checkbox fields are `checked`, if they are checked i should fetch the `id attribute` values from the checkbox and make them as a list or tuple or an array of values
2. I had a django function, that accepts this values and do some processing based on the values, so how to call a url(using GET, something liek that) with the above values from the above jquery

From the above jquery i can able to get the checkbox elements by using a class, but i need to loop through then and get the id value if the checkbox is checked, so how to do this in jquery ?

Try

jQuery(function ($) {
    $("#process_button").click(function () {
        //create an array of checked checkbox ids
        var ids = $('.css-checkbox_latest:checked').map(function (index) {
            return this.id;
        }).get();

        //if nothing is selected alert the user and stop further processing
        if (!ids.length) {
            alert('nothing is selected')
            return;
        }

        //send a request to server using an ajax POST request, it will contains an array of parameters called ids
        $.ajax({
            url: '<url>',
            type: 'POST',
            data: {
                ids: ids
            }
        })
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM