I have some javascript and am creating some html on the fly. What I want to do is add an event handler to each control (they are all “Input” controls) so that if I click on any of them they all fire the same event. I first define a delegate in the initialize section of the code like this:
this.rule_event_handler = Function.createDelegate(this, this.rule_selected);
I have a function shown below that I want all the controls to call when clicked:
rule_selected: function () {}
I add the handler as shown below:
display_rules: function () {
var rulearea = $('#ruleControlArea')[0];
rulearea.innerHTML = "";
for (intI = 0; intI < this.arrRules.length; intI++) {
rulearea.innerHTML += this.create_rule_control(intI, this.arrRules[intI].display);
$addHandlers($('#rule_' + intI)[0], { 'click': this.rule_event_handler }, this, true);
}
},
The problem I then see is that only the last control cause the onclick event to fire. How can I change the code so that all the controls will fire the same event?
I’d use the .live method
add a class
selectableto your rules and add the live event before creating/deleting your rules itemsIf you really want to use the id of your rules, i’d look into your usage of ids; it looks like you’re using the same id many times on the page (you’re using the id query as an array, which i find strange; any specific reason for that?) and that may cause weird behavior.
EDIT
here is a sample