I'm building a cart app in Javascript and jQuery that needs to run some logic whenever a product is clicked. The clicked elements are radio buttons and checkboxes and the code will check if the right conditions are met for adding the product to the cart.
My initial way of trying to do this was to run preventDefault()
at the start of my function, run some logic that decides if it's ok to add the item, and if so, add it to the cart and check the input element.
Looks sort of like this:
$(document).on("click","[data-item]", function(event) {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
if (event) {
event.preventDefault();
}
// pseudo code...
if (conditionIsMet === true) {
cart.addItem(target);
}
}
cart.addItem = function(item) {
products.push(item);
var element = $('[value=' + item.key + ']');
element.prop('checked', true);
};
My problem is that it seems that I can't use element.prop('checked', true);
in my addItem function, since preventDefault stops that.
Can I get around this someway or what route should I go to get my wanted functionality? I really wan't to stop the form elements from getting checked at all and only check or uncheck through my app instead.
It seems that it's not possible to set the checked
property of a checkbox right after preventDefault
was called on it. Try wrapping your prop
call with setTimeout
, which will make sure that the update of the checked
property occurs in another turn of the event loop:
$("#cb").on("click", function(event) {
updateCart(this, event);
});
const updateCart = function(target, event) {
if (event) {
event.preventDefault();
}
// pseudo code...
if (true === true) {
addItem(target);
}
}
const addItem = function(item) {
setTimeout(function() {
$('#cb').prop('checked', true);
})
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb">