We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Capture switch change event and prevent value change

Hello,

I have some switches on a page using signalR for real time updates.  I want users to be able to click a switch control and have it signal a change at the server, this part works properly with signalr.  I then want to leave the switch in its current state until the server sends back a reply that an action is complete and have that event change the switch status.  This event also works properly, but I cant figure out how to prevent the switch from toggling when initially clicked.  Is there a way to prevent the toggle when intercepting the change event?

Thanks!

1 Reply

SI Silambarasan I Syncfusion Team March 5, 2019 12:45 PM UTC

Hi Adam, 
 
Thank you for contacting Syncfusion support. 
 
We have checked your reported requirement ‘To prevent the switch from toggling’ and it can be achievable in EJ2 Switch by using the checked property in change event as like in the below code example. 
 
CODE EXAMPLE: 
 
<ejs-checkbox id="checked" checked="false"> To Change Default behavior of Switch</ejs-checkbox> // Enable the checkbox to change the default behavior. 
<ejs-switch id="unchecked" change="onAcceptChange"></ejs-switch> 
<script> 
    function onAcceptChange() { 
        var instance = ej.base.getComponent(document.querySelector("#unchecked"), 'switch'), 
        checkInstance = ej.base.getComponent(document.querySelector("#checked"), 'checkbox'); 
        if (checkInstance.checked) { 
            $.ajax({ 
                //url: "Home/Index1", invalid url 
                url: "Home/Index", // valid url 
                method: "post", 
                success: function (result) { 
                    instance.checked = false; // set toggle state based on your condition. 
                }, 
                error: function () { 
                    instance.checked = false; 
                } 
            }); 
        } 
    } 
</script> 
 
 
For your convenience, we have prepared the sample that prevents the switch from toggling state in ajax success event based on the checkbox checked state. Please find sample link below. 
 
 
Could you please check the above sample and get back to us if you need further assistance on this? 
 
Regards, 
Silambarasan 


Loader.
Live Chat Icon For mobile
Up arrow icon