skip to Main Content

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>

3

Answers


  1. 1st: ID must be unique don’t use same id for more than one element

    2nd: $("#hidden_onoff") is a label so it has a .text() not .val()

    3rd: You can use one element event to trigger another element event it will be easier to work with

    Take a look at this sample code .. Changing ids to form_onoff and text_onoff

    $(document).ready(function(){
      $("#text_onoff").on( 'click' ,function() {
        $('#onoff').prop('checked' , $('#onoff').prop('checked') ? false : true).change();
      });
    
      $('#onoff').on('change', function(){
        $(this).val(this.checked ? '1' : '0');
        $("#text_onoff").text(this.checked ? 'ON' : 'OFF');
        
        console.log($('#onoff').val());
        
        /*$.ajax({
          url:"/onoff",
          method:"POST",
          data:{ onoff:$("#onoff").val()},
          success:function(data){
            console.log(data)
          }
        });*/
      });  
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form method="post" id="form_onoff" >
      <div class="container">
        <div class="form-check form-check-inline" >
          <input id="onoff" type="checkbox" checked="checked" value="1"/>
          <label class="checkbox-inline" id="text_onoff">
              ON
          </label>
        </div>
      </div>
    </form>
    
    <script>
    
    </script>
    Login or Signup to reply.
  2. You’re setting the value of <label id="hidden_onoff"> rather than <input id="onoff">:

    $('#hidden_onoff').val('1');
    

    However, since you’re using AJAX, it doesn’t seem that you need to change the input’s value anyway. You can define a variable based on whether the input is checked, and send that variable’s value to the server.

    Also, it doesn’t seem that you need both click and change handlers. You can use the change event alone. If your intent is to change the input when its text is clicked, I suggest wrapping both the input and text elements in a <label>.

    … you can nest the <input> directly inside the <label>, in which case the for and id attributes are not needed because the association is implicit (label @ MDN)

    Finally, it looks like you’re executing the AJAX upon page load rather than upon input change. I recommend executing the AJAX from inside your event handler.

    Here’s a demonstration:

    // select the input and label elements and store them as constants
    const $onoff = $('#onoff');
    const $label = $('#onoff_label');
    
    // bind a change event handler to the input
    $onoff.on('change', function() {
    
      // define value and label (1 and ON, or 0 and OFF)
      let cbox_value = $onoff.is(':checked') ? 1 : 0;
      let cbox_label = cbox_value ? 'ON' : 'OFF';
    
      // set label text (ON or OFF)
      $label.text(cbox_label);
    
      // send value via AJAX (0 or 1)
      $.ajax({
        url: "https://reqres.in/api/users",
        method: "POST",
        data: {
          onoff: cbox_value
        },
        success: function(data) {
          // show the result from server
          console.log(data.onoff);
        }
      });
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label>
      <input id="onoff" type="checkbox" checked="checked">
      <span id="onoff_label">ON</span>
    </label>
    Login or Signup to reply.
  3. you need to do a loop for all the input of type check

    $('input[type="check"]').each(function(){
            $(this).val(($(this).prop('checked'))?1:0);
     });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search