3

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?

1
  • Does validateNum use the event object? Commented Apr 18, 2010 at 19:40

3 Answers 3

5

You need to make an anonymous currier:

num1.attachEvent("onkeypress", function() { return validateNum(num1, num2); });  
Sign up to request clarification or add additional context in comments.

2 Comments

OK but how do I detach the event should I need to if I do this? :)
@wlf: Store the handler in a variable.
1

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))
            );
        };
    };
}

3 Comments

Do any real browsers support this?
@SLaks: tbh I'm not sure, ECMAScript 5th was published in Dec 09. Even still, it doesn't hurt to add the method for forwards compatibility purposes.
I'm not aware of any support in released browsers, but it's certainly expected to show up in forthcoming versions (eg. Firefox 3.7).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.