Skip to content

using the bootstrap4-toggler with ajax  #65

@norhan22

Description

@norhan22

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions