0

How can i execute a function after programmatically setting a checkbox to checked? After this completes, I would like to call a function:

$(event.target).parents(".row").first().find(":checkbox").prop("checked", true)

I have tried this but it's not working:

$((event.target).parents(".row").first().find(":checkbox").prop("checked", true), function () {
        Edit();
    });   

Thank you for all of your responses. My issue was that the checkbox was being unchecked in the Edit function

user2370664
  • 381
  • 5
  • 8
  • 30
  • 2
    You're overcomplicating this - just call `Edit()` on the following line of code after setting `prop()`. JS is not multithreaded, so operations are executed in sequence (unless they are explicitly async, which this is absolutely not) – Rory McCrossan Feb 17 '21 at 15:23
  • ^ Right. In case you still want a callback -> https://stackoverflow.com/a/28372632/7867822 – Anurag Srivastava Feb 17 '21 at 15:25
  • Hey, JavaScript checkboxes have a `change` event (see https://stackoverflow.com/questions/32438068/perform-an-action-on-checkbox-checked-or-unchecked-event-on-html-form ) - see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event - does that address your problem? – Benjamin Gruenbaum Feb 17 '21 at 15:25

1 Answers1

0

.prop isn't async, so you can guarantee the next line will be executed after the first one.

Consider this small example:

// Ensure checkbox isn't checked on load
console.log($('#check1').prop("checked"));  // FALSE

// Call .prop
$('#check1').prop("checked", true);

// Call function
edit();

function edit() {

  // Show function result
  $('#edit').text('Call inside edit();');
  
  // Ensure prop has been executed
  console.log($('#check1').prop("checked"));  // TRUE
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="check1" type="checkbox">
<div id='edit'></div>
0stone0
  • 34,288
  • 4
  • 39
  • 64