Petru Lebada
Petru Lebada

Reputation: 1682

Execute javascript before submit

I know the title sound similar with some other threads but it's a little bit different.I have few buttons like those:

<input type=button name=Ok onclick='window.location="www.bla.com/bla.php"'>

When the user press any of them,i want a javascript or jquery code to run, but after,i want to be send to www.bla.com/bla.php.

I have a jquery code for submitting the form:

$( document ).ready(function() {
   $(':button').click(function(){
    document.getElementById('contact').submit();    
    }); 

The jquery code works,but the buttons does not...

Upvotes: 0

Views: 185

Answers (4)

Jasen
Jasen

Reputation: 12412

No javascript will execute after the form is submitted. form submission changes window.location and that stops the javascritpt from the old window.location from executing.

but you can fake it.

  • use jquery forms to submit the form (if CORS will allow that)

  • or have the script at the form destination do a redirect to your desired location.

  • or submit to the desired location and have the script there send the form data to where it should go

Upvotes: 2

dam660
dam660

Reputation: 79

Something like this could do the job?

<input type='button' name='ok_btn' id='ok_btn' value='Ok'  data-href="www.bla.com/bla.php" />

$(document).ready(
    function() {
        $('#ok_btn).on('click',function(){
            // Do your stuff
            // Finally:
            window.location.replace($(this).attr('data-href'));
        });
    }
);

Upvotes: 1

Anand Patel
Anand Patel

Reputation: 3943

try this

<input class="btn" type=button name=Ok data-href="location">

$( document ).ready(function() {
   $('.btn').click(function(){

    // as you have used jQuery selector you can use it here like this 
    $('#contact').submit();   

    var location = $(this).attr("data-href");

    window.location.href  =  location;
    }); 
});

Upvotes: 2

Pupil
Pupil

Reputation: 23958

My solution is jQuery based.

The syntax here is incorrect:

<input type=button name=Ok onclick="www.bla.com/bla.php">

Modify it as:

<input type=button name=Ok data-href="www.bla.com/bla.php">

jQuery:

$( document ).ready(function() {
  $(':button').click(function(){
  var hrefCurr = $(this).attr('data-href');
  document.getElementById('contact').submit();
  window.location.href = hrefCurr;
});

Upvotes: 2

Related Questions