Chameron
Chameron

Reputation: 2984

Call an event from another element

I have button A with

onclick = "alert(1);"

And button B.

How to do, when I click on button B , it should call event on button A ?

click B -> eventB -> eventA

Upvotes: 1

Views: 4436

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185963

HTML:

<button id="buttonA"> Button A </button>
<button id="buttonB"> Button B </button>

JavaScript:

var a = g('buttonA'),
    b = g('buttonB');

function g(s) { return document.getElementById(s); }

a.onclick = function() {
    alert('Button A clicked!');
};

b.onclick = function() {
    alert('Button B clicked!');
    a.click();
}

Live demo: http://jsfiddle.net/TaPWr/1/


Update:

If the Button B is inside an IFRAME then use the top object to reference the window object of the "parent" page. The IFRAME code would be like so:

var b = document.getElementById('buttonB');

b.onclick = function() {
    alert('Button B clicked!');
    top.document.getElementById('buttonA').click();
}

Upvotes: 5

Kris Ivanov
Kris Ivanov

Reputation: 10598

onclick="document.getElementById('buttonAId').click();"

put that on button B

update: if button A is in the form that has iframe where button A is:

onclick="parent.document.getElementById('buttonAId').click();"

assuming both frames are served from the same domain

Upvotes: 1

Related Questions