forked from minhur/bootstrap-toggle
-
Notifications
You must be signed in to change notification settings - Fork 64
Open
Description
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
- the switcher toggles on change immediately and couldn't stop that by neither
e.preventDefault()nore.stopPropagation() - 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
Labels
No labels