How can one execute the jQuery before this Javascript? Currently, I am getting in the logs 2, 1 when I would like to get 1, 2.
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<form method="POST" id="post-form">
<input type="submit" onclick="createDiv();" name="Send" >
</form>
<script>
$(document).ready(
$('#post-form').submit(function(e){
console.log(1);
})
);
</script>
<script>
function createDiv() {
console.log(2);
}
</script>
>Solution :
As you know first click button event is triggering then form is submitting. Therefore you output is logically correct. But still if wanna change the flow you can do some modification to achieve that.
To ensure that the jQuery code executes before the JavaScript code, you can modify your script as follows:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
function createDiv() {
console.log(2);
}
$('#post-form').submit(function(e) {
console.log(1);
createDiv();
});
});
</script>
<form method="POST" id="post-form">
<input type="submit" name="Send">
</form>