简体   繁体   中英

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.

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 );
          });
  }); 

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