Reputation: 10828
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'
See working example: http://jsfiddle.net/1d40qhyx/
I am using $.each()
function to detect the section, remove all the background and add the background-color on selected button. Is the code well coded or 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>
Upvotes: 1
Views: 1504
Reputation: 18859
You can use event delegation
to use only a single listener rather than binding the click event to every of the elements with class updateStatus
.
This should be more performant:
<div id="wrapper">
<div class="section">
<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>
</div>
<div class="section">
<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>
</div>
</div>
$("#wrapper").on("click", ".updateStatus", function(){
var $siblings = $(this).siblings();
var cssClass = ($(this).val() === "complete") ? 'green' : 'orange';
$siblings.removeClass("green orange");
$(this).addClass(cssClass);
});
http://jsfiddle.net/1d40qhyx/2/
Upvotes: 1