0

I have the javascript below that gets all checked box and it works well.

<script>
                function addlist() {
                    var array = []
                    var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')

                    for (var i = 0; i < checkboxes.length; i++) {
                        array.push(checkboxes[i].value);
                    }
                }
</script>

I want to know how to submit the list array to views.py and get it via request.POST['']

Any suggestions?

searcher__dm01
  • 109
  • 1
  • 8
  • What have you tried and where are you stuck? – ggorlen Dec 08 '21 at 01:58
  • I'm trying to store this list somewhere where it can be called by request.POST[''] in views.py, but I don't know how to do that. In HTML there is a way to identify attributes with name="", but in javascript how can I make this call in views and use this list? – searcher__dm01 Dec 08 '21 at 02:02
  • Is this what you're trying to do [appending array to FormData and send via AJAX](https://stackoverflow.com/questions/16104078/appending-array-to-formdata-and-send-via-ajax)? I don't understand why you're using `document.write` instead of sending a request to the server with `fetch` or similar. Before trying to POST an array, you might as well set up POSTing non-array data, then figure out the step to encode an array as form data. As it stands, none of the code shown has anything to do with Django or AJAX. – ggorlen Dec 08 '21 at 02:04
  • document.write was just to test. I removed it. – searcher__dm01 Dec 08 '21 at 02:11
  • I was wondering if there is a way to identify the list array in the views.py function like i do with HTML elements. For example: my_list = request.POST['array'] – searcher__dm01 Dec 08 '21 at 02:13

1 Answers1

1

I solved the question in the follow way:

I created a hidden input to receive the list by javascript:

    <script>
        function addlist() {
            var array = []
            var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')

            for (var i = 0; i < checkboxes.length; i++) {
                array.push(checkboxes[i].value);
            }

            document.getElementById('precedent_list').value = array;
        }
    </script>


<input  type="hidden" style="outline-style: none;" id="precedent_list" name="precedent_list">

And I call the javascript function when the submit button is clicked:

    <p class="w3-center" style="padding-top: 25px; padding-bottom: 25px">
          <button class="w3-round-xxlarge general_button" type="submit" onclick="addlist()">Salvar</button>
   </p>

In views.py I receive the list in the follow way:

my_list = ''
my_list_= []
if 'precedent_list' in request.POST:
    my_list = request.POST['precedent_list']
my_list = my_list.replace(',',' ')
for j in my_list.split():
    my_list_.append(int(j))
searcher__dm01
  • 109
  • 1
  • 8