tim
tim

Reputation: 3903

jquery .on() event map on dynamic elements not working

I have a dynamically created form inside the element #addform with input fields. I am attaching events to the fields like so:

$('input[type=text]').on({focus:function(){console.log('d');}},'#addform')

Why does this not trigger? I read about .delegate() but I think it's supposed to work with .on()

Upvotes: 1

Views: 160

Answers (3)

Matthew Davis
Matthew Davis

Reputation: 142

$('#addform').on('focus','input[type=text]', function(){
   console.log('d');
});

Does the same thing but is more readable I think.

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

I think this is more appropriate:

$('#addform').on({focus:function(){console.log('d');}},'input[type=text]');

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191729

You have the arguments reversed. It should be:

$("#addform").on({...}, 'input[type=text]');

The reason for this is that the actual binding is done to #addform. input[type=text] may not exist when .on is called.

Upvotes: 4

Related Questions