Gcobani Mkontwana

Gcobani Mkontwana

  • 1.2k
  • 765
  • 36.5k

ON/OFF should be a single toggle switch in Jquery

Nov 26 2019 2:53 AM
Hi Team
 
I have some special function in Jquery it does switch the on and off button. Can anyone show me how to improve my logic to have one specific On/OFF button to toggle in Jquery based on this given code. Please show me an example at least will work from there if possible as i know how read the code well. 
 
<div class="form-group"><br>
<div class="col-md-3 text-center">
<button id = "singlebutton" name="singlebutton"
class="btn btn-danger " onclick="BtnOff();">Off</button><br>
</div>
</div>
<br/>
<div class="form-group"><br>
<div class="col-md-3 text-center">
<button id = "singlebtn" name="singlebtn"
class="btn btn-success " onclick="BtnOn();">On</button><br>
 
// button click functionality here.
$('.btnOff').on('click', function(){
BtnOff();
$(this).off('click');
});
$('.btnOn').on('click', function(){
BtnOn();
$(this).off('click');
});
// functionality for button-Off.
function BtnOff() {
$.ajax({
url:'https://api.thingspeak.com/update?api_key=DLQ0F7W5FGVO1I9Q&field8=0',
type:'GET',
data:{
format:'text'
},
success:function(response) {
alert(response);
},
error:function(){
$('#error').text("There was an error processing your request.Please try again");
$('#singlebutton').append(data);
}
});
}
// functionality for On Button.
function BtnOn() {
$.ajax({
url:'https://api.thingspeak.com/update?api_key=DLQ0F7W5FGVO1I9Q&field8=1',
type:'GET',
data:{
format:'text'
},
success:function(response){
alert(response);
},
error:function(){
$('#error').text("There was an error while processing your request.Please try again");
$('#singlebtn').append(data);
}
});
}
 

Brought to you by: JavaScript SDK for Bold BI dashboard and analytics embedding. Free trial.

Answers (3)