0

I am having a bit of trouble on how to apply jquery event helpers on selectors that have been appendTo. I have this code:

$('<input/>').attr({ id: 'submitbtn', type: 'submit', value: 'Click me' }).appendTo('form');

Now, when I try to use click function on this appended submit button nothing happens

$('input#submitbtn').click(function() { // code here });

While it works fine if this element was pure html. How can I make this work? Any help appreciated.

Thanks in advance!

1

1 Answer 1

1

You have to use live events:

$('input#submitbtn').live('click', function(e) {
    /* code here */
})

Regular events are only bound to elements which exist at the time where the event is bound.

PS: I hope you only create one button. IDs must be unique - things will usually break if they aren't. If you plan to create multiple buttons, use classes instead of IDs and . instead of # in the selector.

Sign up to request clarification or add additional context in comments.

2 Comments

@jackJoe: not if he creates the button after binding the handler; @user558134: i'd suggest you to choose a nickname instead of the default one
ok, good point, I didn't realise the OP would append it afterwords.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.