I have two groups of two buttons (status). If you click on "Complete" or "On Hold", it will change the background color of the button. I am using same class name for all the buttons but each group of buttons have data attribute data-section='Park One'
and data-section='Park Two'
I am using the $.each()
function to detect the section, remove all the background and add the background-color on selected button. Is the code well coded? What can be improved?
jQuery:
$(".updateStatus").click(function () {
var buttonValue = $(this).val();
var section = $(this).data("section");
var cssClass = (buttonValue === "complete") ? 'green' : 'orange';
$('.updateStatus').each(function () {
if ($(this).data("section") == section) {
$(this).removeClass("green orange");
if ($(this).val() == buttonValue) {
$(this).addClass(cssClass);
}
}
})
});
HTML
<h2>Park One</h2>
<button class="updateStatus" value="complete" data-section='Park One'>Complete</button>
<button class="updateStatus" value="on hold" data-section='Park One'>On Hold</button>
<h2>Park Two</h2>
<button class="updateStatus" value="complete" data-section='Park Two'>Complete</button>
<button class="updateStatus" value="on hold" data-section='Park Two'>On Hold</button>
.btn
- not that they actually have to be buttons. \$\endgroup\$var $this = $(this)
andvar $updateStatus = $('.updateStatus')
\$\endgroup\$