user1915863
user1915863

Reputation: 51

How to use this in selector in jquery

I am writing a Jquery plugin where I need to use this as a selector. But its not working.

Here's the code of plugin:

$.fn.submitNow=function(onSuccess){
    var thisElement=this;
    $(document).on('submit',this,function(e){
        e.preventDefault();
        $.get($(this).attr('action'),function(data){
            onSuccess.call(thisElement, data);
        });
    });
}

Here is the html snippet (nb. created dynamically):

<form action="demoLink" class="chosen-form">
    <input name="code" type="text">
    <button type="submit">Submit</button>
</form>

Here's the code:

$('.chosen-form').submitNow(function(data){
    alert(data);
});

My guess is this as a parameter in the on() function cannot be used. How to pass this as a selector in on() function?

Upvotes: 0

Views: 74

Answers (2)

Barmar
Barmar

Reputation: 782166

If you create the forms dynamically, you can't use $(selector).widgetName() to bind the handler. You should just use an ordinary function that takes the selector as an argument.

$.submitNow=function(selector, onSuccess){
    $(document).on('submit',selector,function(e){
        e.preventDefault();
        $.get($(this).attr('action'),function(data){
            onSuccess.call(this, data);
        });
    });
};

Then you call it as:

$.submitNow('.chosen-form', function(data) {
    alert(data);
});

Upvotes: 1

Andr&#233; Bonna
Andr&#233; Bonna

Reputation: 807

I do not understand what your plugin will do, but answering your question:

From Jquery documentation, the selector parameter must be a string.

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

[selector]

Type: String

A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

Upvotes: 1

Related Questions