mardi 10 août 2021

How to send AJAX value as 1 when checkbox is checked and 0 when it is not checked?

I have a checkbox it's change text when checked (check is text = on, uncheck is text = off and this value are 0 and 1) I want get value 0 or 1 (check get 1 uncheck get 0) by ajax but I confuse in my code

$("#onoff").click(function() {
  if ($(this).is(':checked')) {
    $("#hidden_onoff").text("ON");
  } else {
    $("#hidden_onoff").text("OFF");
  }
});

$('#onoff').change(function() {
  if ($(this).prop('checked')) {
    $('#hidden_onoff').val('1');
  } else {
    $('#hidden_onoff').val('0');
  }
});

$.ajax({
  url: "/on_off",
  method: "POST",
  data: {
    onoff: $("#hidden_onoff").val(),
  },
  success: function(data) {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="on_off">
  <div class="container">
    <div class="form-check form-check-inline">
      <input id="onoff" type="checkbox" checked="checked" />
      <label class="checkbox-inline" id="hidden_onoff">ON</label>
    </div>
  </div>
</form>



Aucun commentaire:

Enregistrer un commentaire