tags:

views:

17

answers:

3

hi,

im trying to figure out how to trigger a control's event from a javascript function (without touching the actual control itself)

say i have this textbox...

<input type="text" value="" id="my_textbox" onclick="alert('!');" />

then say i was trying to call its onclick event via javascript...

function TriggerTextboxOnClick()
{
  //... call the onclick event of 'my_textbox'
}

any help would be greatly appreciated as this is doing my nut - thanks

p.s. im not actually trying to pop-up an alert box, ive simplified it for illustrations sake

-- LM

+3  A: 

You could just call document.getElementById("my_text_box").onclick(), see also: http://jsbin.com/ixuwo4.

bouke
+1  A: 

Bouke's solution works.

In general, you may want to do somthing like this instead as a good practice:

<input id="my_textbox" onclick="my_textbox_onClick()" />
...
function commonLogic() {
  // Logic that's common to both the onclick event and the *other* code 
}

function my_textbox_onClick() {
  // This function should only contain logic that is triggered by a click on the textbox
  commonLogic();
}
DashK
Although my solution works, from a design perspective, this would be the way to go.
bouke
+1  A: 

couple of things:

  • doing someting via the inline onclick attribute as you've got in your example is not the best way. Attaching event handlers in script blocks is better for accessibility and cleaner, maintainable code.
  • if you're using a library like jQuery already then let the library handle it for you. see code below:

//assuming using jQuery

$('#my_textbox').click(function(){
    //do stuff here
});


//firing the event in some other function
function TriggerTextBoxOnClick(){
    //do stuff here

    $('#my_textbox').click();

}

Ref: More info on inline click handlers: http://www.quirksmode.org/js/events_early.html

You can do the same as the jQuery code with plain old js too:

element.onclick = doSomething;
if (element.captureEvents) element.captureEvents(Event.CLICK);

Read this for more info on doing this with plain JS: http://www.quirksmode.org/js/introevents.html

Moin Zaman