Reputation: 23
I have created several elements dynamically in javascript. These are, among others, range inputs. I want on "input change" event to show the value. Each of these inputs have id like 'probabilitate'+number. The number is a global variable, and is incremented on click event of a button.
When I create dynamically these inputs, the input change event does not work anymore. There is a question on stackoverflow, in which the solution is live event, not on event, and it works, partially. The code is:
$(document).on('change','#probabilitate'+nrBoli, function(){
//something
})
Upvotes: 1
Views: 357
Reputation: 29
You need to use 'class' instead 'id' to get all elements. Using 'id' you get only the first element in the DOM:
Append elements:
var globalProp = 1;
$("#sameContainer").append('<input type="checkbox" id="inputId" class="probabilitate' + globalProp + '"/>');
Set change event:
The change event must be set whenever new elements is appended.
$('.probabilitate' + globalProp).change(function () {
//do action
})
Example:
var globalProp = 1;
function appendInput(){
$("#sameContainer").append('<input type="checkbox" id="inputId_a" value="check this" class="probabilitate' + globalProp + '"/>');
$("#sameContainer").append('<input type="checkbox" id="inputId_b" value="or this" class="probabilitate' + globalProp + '"/>');
$("#sameContainer").append('<input type="checkbox" id="inputId_c" value="or this" class="probabilitate' + globalProp + '"/>');
$('.probabilitate' + globalProp).change(function () {
//do action
})
};
Hope this helps.
Upvotes: 0