I have a input checkbox that has been modified to be buttons one for approve
one for reject
when approved is selected it checks the box etc. Once selected a third button save
submits. If I check the box without using the buttons my script works but then I loose other functionality already associated with the buttons.
The code below is based on Update order status via AJAX in WooCommerce Order received page
How can I listen and detect if the checkbox has been selected even it was checked by selecting the button and not the actual checkbox.
$(document).ready(function() {
$(".wcfa-save-button").click(function() {
if ($("input[type=checkbox]").is(":checked").length > 0) {
alert("Check box is Checked");
$('button.wcfa-save-button').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: "woocommerce_params.ajax_url",
data: {
'action': 'redeem_complete',
'order_id': orerId, // Here we send the order Id
},
success: function(response) {
$('.response').text("Order data successfully fetched.");
console.log("Order data successfully fetched.");
}
});
});
} else {
alert("Check box is Unchecked");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="wcfa-attachment" class="wcfa-hidden" id="wcfa-approved-result" data-id="attachmentID">
<button id="wcfa-approve-button-ID" class="button wcfa-approve-button" data-approval="approved" data-id="attachmentID">Approve</a>
<button id="wcfa-reject-button-attachmentID" class="button wcfa-reject-button" data-approval="rejected" data-id="attachmentID">Reject</a>
<button class="button wcfa-save-button wcfa-disable-during-transition" data-id="attachmentID">Save</button>
Update Was unable to target the checkbox, ended up checking if the approve
button .hasClass
of wcfa-approve-active-button
then sending the submit
$('button.wcfa-save-button').click( function(e){
e.preventDefault();
if ( $('.wcfa-approve-button').hasClass('wcfa-approve-active-button')) {
alert("Check box in Checked");
console.log("Checkbox is Checked");
3
Answers
You cab check if the checkbox is checked or not using "length", you can do something like below:
As this is related to WordPress (WooCommerce) you need to start by
jQuery
first… Then the following will detect if your checkbox is checked or not (on start and on change)…Here is the revisited code:
Tested and works.
a) one set of click listener for checkbox, approve & reject button
b) second click listener for save which checks checkbox state and fires ajax
Stackblitz link – https://stackblitz.com/edit/jquery-1mn3mr?file=index.html