gitbrent/bootstrap4-toggle

using the bootstrap4-toggler with ajax

norhan22 opened this issue · 2 comments

I call an ajax request on change the switcher, and I want to prevent the toggling till the ajax response

My Code

HTML

<input type="checkbox" data-toggle="toggle" class="toggle_switcher" data-onstyle="success" data-offstyle="danger">

JS

   $('.toggle_switcher').change(function () {
       $.ajax({
            url: apiURL,
           type: 'PUT',
           headers:{// some headers here}
           success (res) {
             if (res)  //  toggle
             else     // don't toggle
           }
         })
       })

The Issues that I faced

  1. the switcher toggles on change immediately and couldn't stop that by neither e.preventDefault() nor e.stopPropagation()
  2. Absolutely couldn't use the normal toggle Methods within the change event like $('#toggle-demo').bootstrapToggle('toggle') , it causes an infinite loop

So I did this

   $('.toggle_switcher').change(function (e) {
          const 
          checked = e.target.checked,
          el = $(this),
          toggleToOff = () => {
              el.parent().attr('class', 'toggle btn btn-danger off')
              el[0].value = 'off'
              el[0].checked = false
        
           },
           toggleToOn = () => {
              el.parent().attr('class', 'toggle btn btn-success')
              el[0].value = 'on'
              el[0].checked = true
           },
          updateToggle = () => (checked ? toggleToOn() : toggleToOff()),
          revertToggle = () => (checked ? toggleToOff() : toggleToOn())

           $.ajax({
              url: apiURL,
              type: 'PUT',
              headers:{// headers here}
              success (res) {
                if (res)   updateToggle()  //  toggle
                else   revertToggle()    // don't toggle
              }
        })
     })

I don't know if that the best way to achieve the target but it works well for me till now

Hi @norhan22,
In bootstrap5-toggle there is support for silence toggle method that can resolve your issue but will requiere move your project to bootstrap5.

$('#toggle-demo').bootstrapToggle('toggle', true);

Hi @norhan22,

I've released a new version for bootstrap 4 in palcarazm/bootstrap5-toggle that support silence toggle method.