I'm learning javascript loops and arrays and I'm wondering if I can get all buttons attributes, like in my code when I click on submit button I want to loop through all buttons (with class "seat") attributes named "value" and to set statement if its "value=1" to change background color to red.
<div id="tickets">
<button value="0" class="seat">1</button>
<button value="0" class="seat">2</button>
<button value="0" class="seat">3</button>
<button value="0" class="seat">4</button>
<button value="0" class="seat">5</button>
<button value="0" class="seat">6</button>
<button value="0" class="seat">7</button>
<button value="0" class="seat">8</button>
<button value="0" class="seat">9</button>
<button value="0" class="seat">10</button>
<button id="submit-btn">Submit</button>
</div>
There is a JQuery code
$(".seat").click(function (e) {
e.preventDefault();
let value = $(this).attr("value");
if (value === "0") {
$(this).addClass("active");
$(this).attr("value", "1");
}else if (value === "1"){
$(this).removeClass("active");
$(this).attr("value", "0");
}
});
Here I'm adding value to 1 and everything is working okay, its adding class Active and changing value, now I tryed to make loop and check all buttons values and if its 1 to add class which is changing background color to red, but I just cant figure out how to do that, tryed some solutions didtn worked.
EDIT Tryed with loop like this from @Kenny not working
$("#submit-btn").click(function () {
$(".seat").each((elem) => {
if ($(elem).attr('value') === '1') {
$(elem).addClass('reserverd');
}
});
});
valueattribute to add class for background red? Am I correct? Or you want to do this all in click handler?elemis - it's the index. Call .each as.each((idx, elem) =>and your code will work api.jquery.com/each$(".active").addClass("reserved"). For learning: consider result sets as a whole rather than individual items (like going from procedural programming and OO to SQL)