3gwebtrain
3gwebtrain

Reputation: 15297

How to send parameter with a 'on' listener?

I am not able to send a parameter with on listener. Here is my code:

$.each(this.elements, function(i,element){
            
        var tagName = $(element).prop('type').toUpperCase();
        
        switch(tagName) {
            case "TEXT" :
            case "TEXTAREA" :
                $(element).on('focus input focusout', that.inputHandler, tagName); //not working
            case "SELECT-ONE" : 
                $(element).on('change focusout', tagName, that.selectHandler); //not working
            case "RADIO"      :
            case "CHECKBOX"   :
                $(element).on('change focusout', tagName, that.changeHandler);
        }
        
    });

Example :

this.inputHandler = function (e,tagname) {
          console.log(e,tagname); //i am getting error. how to fix this?
        var val =  $(this).val();
        this.errorHandler(val);
    }

Can anyone suggest me the right way please?

Upvotes: 0

Views: 49

Answers (2)

Lyfing
Lyfing

Reputation: 1916

handler
Type: Function( Event eventObject )
A function to execute when the event is triggered.

When the browser triggers an event or other JavaScript calls jQuery's .trigger() method, jQuery passes the handler an event object, it can use to analyze and change the status of the event.

As the document has presented, you can't pass self-defined data to the handler. But as the on document presents,

.on( events [, selector ] [, data ], handler )

you can pass self-defined data by this way( official example ):

function myHandler( event ) {
    alert( event.data.foo );
}
$(element).on( "click", { foo : "self-define-data" }, myHandler );

Most of the time, read the official document would be more helpful.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

The problem seems to be that the tagName is a string, in such case jQuery will assume it to be a delegated event handler instead of interpreting it as data. so try

$(element).on('change focusout', {tagName:tagName}, that.changeHandler);

then you can access the tagName from the event object like

event.data.tagName

Demo: Fiddle

Upvotes: 1

Related Questions