Emilio Conte
Emilio Conte

Reputation: 1145

No checkbox data in form from a row table where checkbox is selected

In a table, each row contains a checkbox in an unique form like this:

<td class="d-inline-block col-2">
        <div class="form-check">
          <form action="/slider-update/1" method="post" id="check-1">
            <input type="hidden" name="csrfmiddlewaretoken" value="uDIiSPShbE3R2COQDI0qE4SlJGiqsQy8CQ2nQ0jllibaOqH6YsU8TtL7Xy0pF8sI">
            <input class="form-check-input position-static" type="checkbox" id="1" value="is_active" aria-label="...">
          </form>
        </div>
 </td>

Each form is identified with an id formatted with a pk (here: "check-1"). Despite all these clear informations, I can't get my form!

Here is my javascript code:

    $(document).on('click', 'form', function () {
      var rpk = $(this).attr("id");
      var url = $(this).attr("action");
      var form = $('#' + rpk);
      $.post(url, form.serializeArray())
          .done(function (data) {
              alert( data );
          });
  }); 

I get the correct form but it contains only the token, nothing related to the checkbox.

Upvotes: 0

Views: 28

Answers (1)

Hank X
Hank X

Reputation: 2044

You need to set name attribute to your checkbox. jQuery document here serializeArray

that's change your code like this:

 <input class="form-check-input position-static" type="checkbox" id="1" name= "checkbox-1" value="is_active" aria-label="...">

also in your JavaScript code. Don't need to do

var form = $('#' + rpk);

you can just use

$(this).serializeArray()

that's :

    $(document).on('click', 'form', function () {
      var url = $(this).attr("action");
      $.post(url, $(this).serializeArray())
          .done(function (data) {
              alert( data );
          });
  }); 

Upvotes: 1

Related Questions