I'm trying to change the value of a data attribute and the background colour whenever the button is clicked, so it needs to account for multiple clicks as it makes an ajax call on the event click on the element.
What happens so far is that the background colour gets changed and the data-attribute changes, but when clicked for a second time the original data-status
value is picked up in the if statement even though it was changed in the original click.
$(document).ready(function () {
$('.button-create').click(function () {
// assign data from data attributes to variables
var check = $(this).data("value");
var checkID = $(this).data("checkid");
var legend = $(this).data("legend");
var area = $(this).data("area");
var status = $(this).data("status");
// ajaxCall(check, checkID, legend, area, $status)
//change colour when clicked based on status
if($(this).data("status") == 0) {
console.log("Element has been clicked to green");
$(this).css('background', 'green !important');
$(this).attr('data-status','1')
} else if ($(this).data("status") == 1) {
console.log("Element has been clicked to change to red");
$(this).css('background', 'red !important');
$(this).attr('data-status','0')
};
})
})
<html>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<body>
<button class='check-box button-create' data-value='AUDIT' data-checkid='86' data-legend='3' data-area='8' data-status='1' type='submit' name='submit' value='submit'></button>
</body>
</html>
Any help is most appreciated! Thank you