简体   繁体   中英

How to call a JS function before a jquery button click(click through selector)

I want to call a JS function when a button is clicked and then continue execution of below jquery script

Form :

<form id="my_form">
  <button type="button" id="Bshift" onclick="validation()">Clear</button>
</form>

Pure JS Function:

function validation(){
    // this has to be executed  first
    // do something here..
}

Jquery:

$(document).ready(function(){
    $('#Bshift').submit(function(){
    // this has to be executed  second
    // do something here.
    }
});

I would like to know is how I execute my function before my jquery submit.

HTML:

  <form id="my_form">
    <button type="button" id="Bshift">Clear</button>
  </form>

JS:

$(document).ready(function(){
   $('#Bshift').on('click', function(){ // I think this should be click event because you're not submitting your page you're just clearing it based on "CLEAR"
     validation();
   }

   function validation(){
    do something here..
   }
 }

Note: Your function must be outside the event triggers.

Call your validation function inside submit call.

$(document).ready(function(){

        $('#Bshift').submit(function(){
        validation()
        do something here.
        }
    }

HTML Code

<button type="button" id="Bshift" >Clear</button>

You have one more option to submit the form through ajax after validation.

$('my_form').on('submit', function(e) {
    e.preventDefault();
    if (validation()){
        $.ajax({...});
    }
});

Edited code, please test my code.

<script>
function validation(){
    alert('How are you?');
}

$(document).ready(function(){
     $('#Bshift').click(function(){
         validation(); 
         alert('Fine and you?');           
     });
 });
</script>

<form id="my_form">
<button type="button" id="Bshift">Clear</button>
</form>

Demo

Invoke validation function on form submit event

$(document).ready(function(){
    validation(); // function call

    $('#my_form').submit(function(){  //form submit event
    // do something here.
    }

});


function validation(){
 // do something here..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM