Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP jquery set checkbox value if checked or unchecked and post

I want to set value for the check when it is unchecked. But every time I post my data whatever it is checked or unchecked, the value will be '1'

I tried to set !isset($check) in post.php, but the value also will be 1.

How can I set the different value when I uncheck the checkbox.

<input type="checkbox" id="check" name="check" value="1">

The jquery code is below:

var check = $('#check').val();
var Data = {check:check};
$.ajax({
    type:"POST",
    url:"post.php",
    data:Data,
    beforeSend: function() {
        $("#btn-submit").html('sending');
    },
    success: function(data) {
    }
});
like image 761
LamSam Avatar asked Mar 04 '26 07:03

LamSam


1 Answers

You should use is(':checked') to determine whether the checkbox is checked or not:

$("#check").on('change', function() {
  var checkFlag = 'unchecked';
  if ($(this).is(':checked')) {
    checkFlag = 'checked';
  }

  console.log(checkFlag);

  $.ajax({
    type: "POST",
    url: "post.php",
    data: {
      check: checkFlag
    },
    beforeSend: function() {
      $("#btn-submit").html('sending');
    },
    success: function(data) {}
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check" name="check" value="1">
like image 173
Milan Chheda Avatar answered Mar 06 '26 19:03

Milan Chheda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!