Switch toggle return to previous state when I click "No" in the alert prompt

react toggle button state
react toggle on click
react use state to toggle an element
react hooks
jquery toggle switch
react switch component on click
usestate toggle true false
react-toggle display onclick

I created a switch toggle that allows the system administrator to activate/deactivate the login access of an account.

After the admin click the switch toggle (the switch moving from state 1 to 0), it will prompt via alert box a confirmation (Do you want to activate / deactivate this account? Yes | No), whenever I click "no," I want it to return to its previous state (from 0 to 1).

I manage to successfully do this if the state is "1" [The account is activated], but when it's the other way around, from status 0 to 1, the switch toggle doesn't return back to its previous state and gets stuck to state 1.

It still sends the proper POST command tho (e.g. deactivates the account if it's activated, and vice versa), but the visual display is wrong.

This is my code.

Javascript for the toggle switch

var chk;
    $(document).on('change', '.btn-change-status', function(e) {
      e.preventDefault();
      chk = $(this);
      var switch_status = $(this).attr('data-status');
      var account_status = (switch_status == 1) ? 0 : 1;
      var id  = $(this).attr('data-id');
      var confirm_alert = (switch_status == 1) ? confirm("Are you sure you want to deactivate this account?") : confirm("Are you sure you want to activate this account?");
        if (confirm_alert == true) {
         $.ajax({
              url: "/user/update-status",
              type: "POST",
              data: {
                _token: "{{csrf_token()}}",
                id: id,
                status: account_status
              },
              success: function(data) {
                if (data.success === true) {
                  alert("Account Successfully Updated!");
                  location.reload();
                }
              }

            });
        }
        else {
          if(chk.checked) {
            chk.prop("checked", false);
          }
          else {
            chk.prop("checked", true);
          }
        }
    });

EDIT: added the HTML part of the switch, although it's still in javascript coz I attached it to a dataTable.

HTML of the dataTable

 <div class="card mb-3">
            <div class="card-header">
              <i class="fas fa-table"></i>
              Accounts Management</div>
            <div class="card-body">

              <button type="button" id="btn-add-account" class="btn btn-primary">Add Account</button>
              <div class="table-responsive mt-3">
                <table class="table table-bordered dt-responsive" id="table-accounts" width="100%" cellspacing="0">
                  <thead>
                    <tr>
                      <th class="hidden">ID</th>
                      <th>Username</th>
                      <th>Email</th>
                      <th>Role</th>
                      <th>Date Created</th>
                      <th style="width: 15.5%">Actions</th>
                    </tr>
                  </thead>
                  <tfoot>
                    <tr>
                      <th class="hidden">ID</th>
                      <th>Username</th>
                      <th>Email</th>
                      <th>Role</th>
                      <th>Date Created</th>
                      <th style="width: 15.5%">Actions</th>
                    </tr>
                  </tfoot>
                  <tbody>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

        </div>
        <!-- /.container-fluid -->
      </div>

Javascript of the dataTable

$(document).ready(function() {
    getRoles();
    var accounts;
     $('#account-management').addClass('active');

    accounts = $("#table-accounts").DataTable({
        ajax: {
          url: "/users/get-all-users",
          dataSrc: ''
        },
        responsive:true,
        "order": [[ 7, "desc" ]],
        columns: [
        { data: 'id'},
        { data: 'username' },
        { data: 'email'},
        { data: 'role.id'},
        { data: 'created_at'},
        { data: null,
          render: function ( data, type, row ) {
            var html = "";
            if (data.status == 1) {
              html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
            } else {
              html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
            }
              html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
              html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";

            // <button type='button' class='btn btn-primary btn-sm btn-edit' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button> 
            // html += "<button class='btn btn-danger btn-sm btn-delete' data-id='"+data.id+"' data-account='"+data.id+"'>Remove</button>";

            return html;
          } 
        },
        ],
        columnDefs: [
        { className: "hidden", "targets": [0]},
         { "orderable": false, "targets": 4 }
        ]
    });

Thank you!

There are too many values that represent the same thing. You only need two values:

  1. id: [type: String] id of the checkbox.
  2. status: [type: Boolean] By default a checkbox value is true if checked and false if not checked.

In this case you don't need any data-* attributes, but if you still think you do, use .data() method instead:

$('.status').data('id') // Returns the value of `data-id` on each `input.status`

If for some reason you find that you need to use more values for such a trivial task you need to reevaluate your code fundamentally. Details are commented in demo, it uses a live test server to verify what was sent to it.

/* This function extracts the value of each output.member and then assigns a 
   modified version of the value as the id of the checkbox that follows (input.status)
   This is not required to answer the OP's question and is intended just to provide each
   checkbox with a unique id */
$('.member').each(function(index) {
  let user = $(this).val().split('@')
  let id = user[0] + '-' + index;
  $(this).next('.status').attr('id', id);
});

// Any change event occuring on any input.staus (checkbox)...
$('.status').on('change', function(e) {

  // A boolean that reflects the checkbox "check status"
  let checked = $(this).is(':checked');
  
  // A simple confirm...
  let changed = confirm("Are you sure you want to change this account?");
  
  //... if user cancels...
  if (!changed) {
  
    /* ...ternary: [?][if checkbox is checked] - [uncheck it] [:][otherwise] - [check it]
    [return][Terminate function - don't do anything else] */
    return checked ? $(this).prop('checked', false) : $(this).prop('checked', true);
  }
  
  /* function continues here if user confirmed by clicking "OK"
     The data will be posted to a live test server.
     A link will appear at the bottom, follow the directions to verify response */
  let ID = this.id;
  let active = checked ? 1 : 0;
  $.ajax({
    url: "http://ptsv2.com/t/status/post",
    type: "POST",
    data: {
      id: ID,
      status: active
    },
     success: function() {
       $('.response').show();
    }
  });
});
:root {
  font: 16px/1 Arial
}

label {
  display: block;
  margin: 8px 0 0 0;
}

.member {
  display: inline-block;
  width: 25ch;
  vertical-align: middle
}

.status {
  display: inline-block;
  vertical-align: middle
}

.response {
  display: none;
  cursor: pointer;
  width: 99vw
}

.response * {
  display: block;
  margin: 8px auto;
  width: 90%
}
<form id='admin-panel'>
  <fieldset class='member-status'>
    <legend>Member Status</legend>
    <label>
    <output class='member'>zer00ne@gmail.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>tech.artificer@gmail.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>joker666@4chan.org</output>
    Status: <input class='status' type='checkbox'>
    </label>
    <label>
    <output class='member'>byte.my@ss.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>bruce@wayne.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>clark.kent@dailyplanet.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
  </fieldset>
  <hr>
  <output class='response'>
    <a href="https://ptsv2.com/t/status/d/latest" target='view'>Click then scroll down to <i style='display:inline'>Parameters</i> inside the iframe below</a>
    <iframe name='view'></iframe>
  </output>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Change State whenever button is clicked back and forth in React , You can just toggle the state. Here's an example using a Component: class ButtonExample extends React.Component { state = { status: false }� A stateless component, or ‘dumb’ component, is a component that does not control its own state. As a result, it requires another component to keep track of the React switch component’s state. Our React switch component is going to be a stateless component. Therefore, it requires us to pass a value from a parent component through its props.

Should a toggle button show its current state or the state to which it , Can you tell if the switch is ON currently, or if it will go on if you move/click/tap the slider? Is the text obvious? Is "ON" here a state(adjective) or action(verb)?� Since switching to Windows 10, Alt + Tab does not toggle to previous screen in a number of case, i.e. you have to hit Alt + Tab twice to go to the previous screen or go through the thumbnail screens. It sounds small but being able to toggle to the previous screen by hitting Alt + Tab saves me lots of time.

Because you are using class selector '.btn-change-status'

chk = $(this);

chk is now a collection with 1 element. To check whether it is checked use

chk.prop('checked')

or

chk[0].checked

Managing Common Toggle Switch State When Changing Bottom , Blog � Case Studies � Industry Reports � Press Release Setting toggle state to ON in home screen doesn't change toggle state in setting screen and it can be seen OFF. previousState ); <Switch trackColor={{ false: colors.white, true: default: return state; } }; export default headerSwitchToggleReducer;. enabled - can be either a boolean or a function that returns a boolean, and it determines the state of the toggle switch when it is rendered. onStateChanged - is a callback function that will be called when the state of the toggle switch changes. This is useful for triggering actions on the parent component when the switch is toggled.

You are calling the ajax and trying to toggle your input at the wrong event. You have to handle those events on the yes button of the popup not in the change event.

The code should clear it out.

 $(document).on('change', '.btn-change-status', function(e) {
  e.preventDefault();
  var chk = $(this);
  var switch_status = $(this).attr('data-status');
  var account_status = (switch_status == 1) ? 0 : 1;
  var id  = $(this).attr('data-id');
  popUpConfirmation(id, status);
});

function popUpConfirmation(id,status) {
   //popup opens here is visible 
   $("#ok-button").data("id", id);
    $("#ok-button").data("status", status);
}

$("#ok-button").on('click', function() {
  var id  = $(this).attr('data-id');
  var status = $(this).attr('data-status');

  var checkbox = $("input[data-id='"+id+"']");
  if(checkbox.prop('checked')) {
     checkbox.prop('checked',false);
  } else {
     checkbox.prop('checked',true);
  }

   $.ajax({
          url: "/user/update-status",
          type: "POST",
          data: {
            _token: "{{csrf_token()}}",
            id: id,
            status: account_status
          },
          success: function(data) {
            if (data.success === true) {
              alert("Account Successfully Updated!");
              location.reload();
            }
          }

        });

});

$("#cancel-button").on('click', function() {
  //close or hide the popup
});

For the popup create a view. This can be anything a div or a button, or you can use modal-view popups. the main key thing is the triggering buttons.

<div class="popup">
  <input type="button" id="ok-button"></input>
   <input type="button" id="cancel-button"></input>
</div>

This should fix your view issue without changing your code much. You can shorten the code using ternary operator. But I want to keep it simple for others to be able to understand too.

Fell free to ask if you have any queries.

I hope this helps...Happy coding.

.toggleClass(), toggleClass( className, state ) A function that returns one or more space- separated classes or an array of classes to be toggled in the class attribute of each element in the Toggle the class 'highlight' when a paragraph is clicked. It's important to return the previous state for any unknown action. #Note on Object.assign. Object.assign() is a part of ES6, and is not supported by older browsers. To support them, you will need to either use a polyfill, a Babel plugin, or a helper from another library like _.assign(). #Note on switch and Boilerplate

How To Build a Custom Toggle Switch with React, In this tutorial, you will build a custom toggle switch component with React. that returns a boolean , and it determines the state of the toggle switch when it is Let's go ahead and add the method that toggles the switch when it is clicked. 1193-Q/20B Double Pole Momentary Toggle Switch, Center Off, Spade Terminals T7-211E1 Otto Sealed Double Momentary Toggle Switch, Spring return to center off

Use State to Toggle an Element React - JavaScript, setState = ({ visibility: true }) // change code above this line render() { if (this.state. visibility) { return ( <div> <button onClick={this.toggleVisibility}>Click Me</button> � Buttons, check boxes, radio and toggle buttons don't have the BackColor property so they can't do that. An alternative that might(?) be acceptable would be to use a text box control with some VBA code in its Click event procedure to toggle the value: Me.textboxname = Not Me.textboxname . and use Conditional Formatting to affect the back color.

Buttons and Switches, An automatic mechanism (i.e. a spring) returns the switch to its default position immediately afterwards, restoring the In Tasmota a Switch is any switch or push -button additionally connected to a free GPIO. By default a switch toggles the corresponding power state (f.e. Switch1 controls Power1 ). Previous Bluetooth. Bootstrap Toggle is a jQuery plugin/widget that converts plain checkboxes into responsive toggle switch buttons. Made for Bootstrap 4! This page and all of the switch buttons shown are running on Bootstrap 4.3

Comments
  • This helped me solve my problem, thank you! Also, I'll take note of what you said about the use of values, thank you again !! :))
  • That's great. Happy coding!