confirm before submit using toggle button

351 views Asked by At

I have a enable/disable button for user ability. I want to add a confirmation before it gets turned on/off.

<input type="checkbox" id="switch1" checked data-switch="bool"/>
<label for="switch1" data-on-label="On" data-off-label="Off"></label>

js:

function(){
// I want to write a confirmation code here....
api_call(url, data, method)
}

// if not confirmed...
// return false..and dont toggle the button...

However, in my case (intially button on) its not sending the request if not confirmed but it will toggle the button (button Off). After I refresh, it sets to previous value.. (button on)

Please help me not to toggle the switch when request is not sent when not confirming and likewise

2

There are 2 answers

0
Moksh Chadha On

Hi you can use the confirm dialogue present in JS the confirm(...) will return true or false based on user selecting Yes or No

const isConfirmed = confirm('Toggle button?')  
if(isConfirmed) {
  // ... run your function
}


1
Akim Korhonen On

You can use promise to solve your problem.

Using promises ensures that the UI state is not updated until the confirmation is resolved and the API call is completed successfully.

let confirmed = false;

const confirmAction = () => {
  return new Promise((resolve, reject) => {
    const isConfirmed = window.confirm('Do you confirm it?');
    confirmed = isConfirmed;
    
    if(confirmed) {
      resolve();
    } else {
      reject(new Error('Confirmation rejected.'));
    }
  });
 };
 
 const makeApiCall = (url, data, method) => {
    //API call implementation here
    //...
    //Return a promise that is based on the API response
 }
 
 const toggleButtonState = () => {
  confirmAction()
    .then(() => makeApiCall(yourUrl, yourData, yourMethod))
    .then(() => toggleButton())
    .cateh((error) => console.error(error));
 };
 
 const toggleButton = () => {
  if(confirmed) {
    //Toggle the button here
    //...
  }
 }