jquery swtichery additional switches are added

84 Views Asked by At

I'm using js-switch for representing on-off switch of a power source.

I get the response from the device and use the response to check or uncheck the button programatically.

Now, the problem is when ever I get a response, number of switch increases. This should not happen. This is hove I've tried:

if($myDiv.length == 0){
                        console.log("not created");
                        $("#display").append(
                            $("<div>").attr({ "id": "powerDiv", "class": "animated flipInY col-lg-6 col-md-6 col-sm-12 col-xs-12" }).append(
                                $("<div>").attr({"class":"tile-stats"}).append(
                                    $("<div>").attr({"class":"count"}).append(
                                        $("<img>").attr({"src":"images/power.png", "class":"module-icon"}).append(" Power")
                                    ).append(
                                        $("<span>").attr({"style":"font-size: 16px;"}).append("Power")
                                    ).append(
                                        $("<div>").attr({ "class": "pull-right paddingRight" }).append(
                                            $("<input>").attr({ "class": "js-switch powerSwitch", "name": "powerSwitch", "type": "checkbox" })
                                        ).attr("onclick", "javascript:Check();")
                                    )
                                )
                            )
                        );
                    } else {
                        console.log("already created");
                    }

                    elems = document.querySelectorAll('.js-switch');
                    mySwitch = new Switchery(elems[elems.length - 1], {
                        color: 'rgb(38,185,154)',
                        jackColor: 'rgb(255,255,255)'
                    });

                    if(on_off == "on") {
                        setSwitchery(mySwitch, true);   
                    } else if(on_off == "off") {
                        setSwitchery(mySwitch, false);  
                    }

When ever I get the response, it gets checked or unchecked, but one more switch gets added. That should not happen. I guess the mistake is with elems[elems.length - 1].

What should I change so that no additional switch is created and the response is handled with the same switch?

0

There are 0 best solutions below