I have dynamically generated some input tags for a web application.
JavaScript
x
25
25
1
function FormElement () {
2
3
this.formElement = $('<div class="formElement"></div>');
4
this.formElement.append('<label for=""></label>');
5
this.formElement.append('<input type="text" />');
6
7
FormElement.prototype.addIds = function (id) {
8
this.formElement.find('label').attr({'for':id});
9
this.formElement.find('input').attr({'id':id});
10
return this.formElement;
11
};
12
FormElement.prototype.addLabelText = function (value) {
13
this.formElement.find('label').html(value);
14
};
15
FormElement.prototype.addInputValue = function (value) {
16
this.formElement.find('input').attr({'value':value});
17
};
18
FormElement.prototype.addClass = function (className) {
19
this.formElement.attr({'class':className});
20
};
21
FormElement.prototype.append = function (selector) {
22
$(selector).append(this.formElement);
23
};
24
}
25
The appended elements do not seem to have associated click, select etc.. events. I read you can you .on()
. I would like to associate all possible events to all types of elements in a general way. What is the best way to go about this?
Advertisement
Answer
Suppose you want to assign a default behavior on click event for all inputs with a specific class, say ‘foo’:
JavaScript
1
4
1
$(document).on('click','input.foo', function(){
2
/* your function here */
3
});
4
If you don’t go this way and try the following:
JavaScript
1
4
1
$('input.foo').click(function(){
2
/* your function here */
3
});
4
then the behavior will be added only to existing elements, not to those added after the script executed.