tags:

views:

48

answers:

3

I have the following home-grown jquery plugin:

(function($) {
    $.fn.defaultButton = function(button) {
        var field = $(this);
        var target = $(button);

        if (field.attr('type').toLowerCase() != 'text')
            return;

        field.keydown(function (e) {
            if ((e.which || e.keyCode) == 13) {
                console.log('enter');
                target.click();
                return false;    
            }
        });    
    }
})(jQuery);

I'm using it like so:

$('#SignUpForm input').defaultButton('#SignUpButton');

$('#SignUpButton').click(function(e) {
    console.log('click');
    $.ajax({
        type: 'post',
        url: '<%=ResolveUrl("~/WebServices/ForumService.asmx/SignUp")%>',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: JSON.stringify({
            email: $('#SignUpEmail').val(),
            password: $('#SignUpPassword').val()
        }),
        success: function(msg) {
            $.modal.close();
        }
    });
});

The first time, it works. The second time, nothing happens. I see enter and click the first time in the firebug log, but the second time I only see the enter message. It's almost like the button's click handler is being unregistered somehow. Any thoughts?

+1  A: 

Sounds very much like there's something in the ajax success handler that's modifying the part of the DOM containing the #SignUpButton and thus killing all event handlers associated with it. Try the live method instead:

$('#SignUpButton').live('click', function(e) {
    ...
});
Darin Dimitrov
Ahhhh yeah. I'm using simplemodal which clones the elements and breaks the event handlers. You and SLaks both nailed it, but I'll give you the answer since you posted first.
Chris
+1  A: 

You're probably resetting the HTML containing the button, which will re-create the <button> element from scratch (without any event handlers).

To fix this, you can add the event handler using the live function, which will handle the event on all elements matching the selector, no matter when they were created.

SLaks
+1  A: 

Not answering the question, but you should make this chainable, as it's a useful plugin :)

(function($) {
  $.fn.defaultButton = function(selector) {
    if (this.attr('type').toLowerCase() != 'text')
        return this;
    this.keydown(function (e) {
        if ((e.which || e.keyCode) == 13) {
            console.log('enter');
            $(selector).click();
            return false;    
        }
    });
    return this; 
  }
})(jQuery);

Also, note that this is already a jQuery object, no need to clone it.
Making this wiki, feel free to improve it :)

Nick Craver
Thanks for that. I'm new to jquery plugins and was just copying / modifying an existing plugin. Guess I missed the "return this;" statement.
Chris