0

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.

3
  • This is a very common error. You want to assign the function validation to yourr click handler. What you instead do is assign whatever the execution of that function returns by assigning the function execution validation() to the onclick handler. Commented Sep 1, 2015 at 6:06
  • I think you're confused. In jquery. Commented Sep 1, 2015 at 6:08
  • see this demo link jsfiddle.net/oaefktpb/4 Commented Sep 1, 2015 at 6:29

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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

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

Comments

0

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..
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.