I have four buttons, each deciding which speed the fan in a hotel room should have. SO if the user clicks on one button other buttons should be in OFF mode. Any ideas on how to achieve it?
Now I have four buttons that users can turn on simultaneously, which does not make sense for my application.
$("#wentAOnOff").click(function() {
$.ajax({
url:'do',
type:'POST',
data: {
actions:[
{action: "set", what: "mbt", id: "1175", val: 1},
{action: "set", what: "mbt", id: "1062", val: 1},
]
},
success: function(res) {
},
error : function() {
}
});
});
$("#went1OnOff").click(function() {
$.ajax({
url:'do',
type:'POST',
data: {
actions:[
{action: "set", what: "mbt", id: "1176", val: 1},
{action: "set", what: "mbt", id: "1062", val: 1},
]
},
success: function(res) {
},
error : function() {
}
});
});
$("#went2OnOff").click(function() {
$.ajax({
url:'do',
type:'POST',
data: {
actions:[
{action: "set", what: "mbt", id: "1177", val: 1},
{action: "set", what: "mbt", id: "1062", val: 1},
]
},
success: function(res) {
},
error : function() {
}
});
});
$("#went3OnOff").click(function() {
$.ajax({
url:'do',
type:'POST',
data: {
actions:[
{action: "set", what: "mbt", id: "1178", val: 1},
{action: "set", what: "mbt", id: "1062", val: 1},
]
},
success: function(res) {
},
error : function() {
}
});
});
CodePudding user response:
it's not that clear to me what is the problem, turn off the 3 other buttons or the ajax calls? What doesn't make sense?
Anyway, you can iterate all the buttons on every click
and switch off the ones that are not the button the user clicked on. You can use jQuery to get all the buttons and iterate them. Because you have the ID of the clicked element you can turn off all the other buttons.
CodePudding user response:
Use a class and data attributes
const $went = $(".went"); // all 4 buttons by class
$(".went").on("click", function() { // any of them
const id1 = this.dataset.id1;
const id2 = this.dataset.id2;
$(".went").removeClass("active");
$(this).addClass("active");
/*
$.ajax({
url:'do',
type:'POST',
data: {
actions:[
{action: "set", what: "mbt", id: id1, val: 1},
{action: "set", what: "mbt", id: id2, val: 1},
]
},
success: function(res) { },
error : function() { }
});
*/
});
.active { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-id1="1175" data-id2="1062">Off</button>
<button data-id1="1176" data-id2="1062">Off</button>
<button data-id1="1177" data-id2="1062">Off</button>
<button data-id1="1178" data-id2="1062">Off</button>