DomingoSL
DomingoSL

Reputation: 15494

Bind two function to same button

It's valid to do something like:

<form id="legalopt">
    <button type="submit" id="confirmopt" onclick="function2();">Click ME!</button>
</form>

$('#legalopt').submit(function(e){
    e.preventDefault();
    function1();
}

As you can see, funcion1() is fired when the form is submitted by the submit button and also function2() is called because the onlick call of the button.

Is this valid? Is cross-browser compatible?

Upvotes: 3

Views: 320

Answers (3)

Milan and Friends
Milan and Friends

Reputation: 5610

Whoever voted down my answer, here's a Fiddle

<form id="legalopt">
  <button type="submit" id="confirmopt" onclick="function1();function2();">Click ME!</button>
</form>

<div id="box"></div>


#box {
  position: absolute;
  width: 150px;
  height: 150px;
  top: 150px;
  left: 12px;
  border: 1px solid gray;
}



$(function() {

  $('#legalopt').submit(function(e) {
    e.preventDefault();
    function1();
    function2();
  });

  function function1() {
    $('#box').stop().animate({ left: '250px' }, 600);
  }
  function function2() {
    $('#box').css({ background: '#900' }).animate({ left: '12px'}, 600);
  }

});

Upvotes: -1

Suresh Atta
Suresh Atta

Reputation: 121998

I would prefer ,Since they both are executing at same time,

$('#legalopt').submit(function(e){
  e.preventDefault();
  function2();
  function1();
});

Upvotes: 6

Talha Akbar
Talha Akbar

Reputation: 10030

If you want to execute function in order then it will be nice to pass the function as argument to the function which is to be called first.

function1(function2);
...
// At the end of function1's code
function2();

Upvotes: 1

Related Questions