I have dynamically generated some input tags for a web application.
function FormElement () { this.formElement = $('<div class="formElement"></div>'); this.formElement.append('<label for=""></label>'); this.formElement.append('<input type="text" />'); FormElement.prototype.addIds = function (id) { this.formElement.find('label').attr({'for':id}); this.formElement.find('input').attr({'id':id}); return this.formElement; }; FormElement.prototype.addLabelText = function (value) { this.formElement.find('label').html(value); }; FormElement.prototype.addInputValue = function (value) { this.formElement.find('input').attr({'value':value}); }; FormElement.prototype.addClass = function (className) { this.formElement.attr({'class':className}); }; FormElement.prototype.append = function (selector) { $(selector).append(this.formElement); }; }
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’:
$(document).on('click','input.foo', function(){ /* your function here */ });
If you don’t go this way and try the following:
$('input.foo').click(function(){ /* your function here */ });
then the behavior will be added only to existing elements, not to those added after the script executed.