minil
minil

Reputation: 7145

How to pass parameter to the attachEvent Javascript function

I have to pass a parameter the validateNum Javascript function (e.g. num1, num2)

if (num1.attachEvent) {
 num1.attachEvent("onkeypress", validateNum);  
}

How to pass? Can I get a code sample?

Upvotes: 3

Views: 9052

Answers (3)

Gabriel Darezzo
Gabriel Darezzo

Reputation: 21

Finnaly i get solution to pass 'this' as a parameter. if anyone get here search for this(kkkk)....

<input type="checkbox" name="ch_aceito" id="ch-aceito" value="1" />


<script type="text/javascript">
    "use strict";

    var el = document.getElementById("ch-aceito");

    function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
    }

    //alert(isIE());

    if (document.addEventListener) {
        //console.log('here');
        el.addEventListener("click", getPost, false);
    } else {
        el.attachEvent("onclick", function() { 
            getPost(el);
        });  
    }

    function getPost(el){
        if(isIE() && isIE() <= 8){
            alert(el.value);
        } else {
            alert(this.value);
        }
    }
</script>

I get isIE from here:

Detect IE version (prior to v9) in JavaScript

Upvotes: 1

Andy E
Andy E

Reputation: 344773

Aside from SLaks' answer, in ECMAScript 5th Edition implementations you can use the bind method:

num1.attachEvent("onkeypress", validateNum.bind(null, num1, num2));

In implementations that don't support the method you can either use the Prototype JS framework or just add the method to the Function prototype with this snippet:

if (!('bind' in Function.prototype)) {
    Function.prototype.bind= function(owner) {
        var that= this;
        var args= Array.prototype.slice.call(arguments, 1);
        return function() {
            return that.apply(owner,
                args.length===0? arguments : arguments.length===0? args :
                args.concat(Array.prototype.slice.call(arguments, 0))
            );
        };
    };
}

Upvotes: 1

SLaks
SLaks

Reputation: 888185

You need to make an anonymous currier:

num1.attachEvent("onkeypress", function() { return validateNum(num1, num2); });  

Upvotes: 5

Related Questions