2

How to handle multiple JS events to call same function.. please look at the code..

My requirement is to check uniqueness of Client Code entered in a textbox.. So I'm using something like this:

My code:

<input type="text" 
onblur="function1(arg1,arg2)" 
onclick="function1(arg1,arg2)"
onfocus="function1(arg1,arg2)">

So, is there any other better way to rewrite this code?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Disha Goyal
  • 624
  • 12
  • 22
  • 1
    I don't see anything wrong with your code, although I'd personally use `element.attachEventListener` to make it neater. – LonelyWebCrawler Aug 17 '12 at 03:33
  • Ya.. it works fine for me.. but I am looking for an alternate as my piece code looks too messy.. I actually have a big JS function call.. – Disha Goyal Aug 17 '12 at 03:40

2 Answers2

7

Plain JS:

window.onload=function() {
  var fld = document.getElementById("yourfieldid");
  fld.onblur=fld.onfocus=fld.onclick=function() {
    function1(arg1,arg2);
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

If you can use jquery you could do something like this example:

$('#foo').on('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

reference: http://api.jquery.com/on/

Depending on what your goal is though you might want to bind to a different event that more clearly identifies the need for your use-case. Perhaps onChange?

Carth
  • 2,303
  • 1
  • 17
  • 26
  • No.. I have no idea about jquery.. have not tried it either.. Just a way.. that can make this code clean.. – Disha Goyal Aug 17 '12 at 03:38
  • "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. " – mplungjan Aug 17 '12 at 04:51
  • @mplungjan Thanks, mp! I've updated my answer to reference the more recent method you referenced. – Carth Aug 17 '12 at 12:39