Reputation: 43
For single (first input box) I'm successfully get the keyup event but it's not working for every fields I want to calculate sum of all the fields and want to show them in total.
My code for javascript is here.
$(document).ready(function(){
var b = 1;
$('#mon'+b).keyup(function() {
alert('Monday');
$('#mon'+b).each(function(){
b++;
});
alert(b);
});
});
I'm able to get the dynamic id like mon , mon1 , mon2. And if I fire below code in console keyup event is works.
$('#mon2').keyup(function() {
alert('Monday');
});
EDIT:-
var b = 1;
alert('Monday');
$('#mon'+b).each(function(){
$('#mon'+b).keyup(function() {
b++;
alert(b);
});
});
alert(b);
Edit :- 2 https://jsfiddle.net/b71a32qL/8/
Upvotes: 0
Views: 1399
Reputation: 2158
According to your js fiddle link. You have to make two change,
Change 1 :- (Add class mon
in input type)
<input type="number" step="any" name="mon1" id="mon1" class="mon cell-size" placeholder="mon">
Change 2 :- Replace your javascript with following javascript.
$(document).on("keyup",'.mon', function(){
var sum = 0;
alert('Monday');
$('.mon').each(function(){
var $value = this.value;
if($value){
sum+=parseFloat($value);
}
});
$('#mon_total').val(sum);
});
So, through Jquery you can make total of each class mon
using each()
method.
Please Let me know that it's working or not ?
You can change your total with id mon_total
.
Upvotes: 1
Reputation: 530
var b = 1;
$(document).on("keyup",'#mon'+b, function(){
alert('Monday');
$('#mon'+b).each(function(){
b++;
});
alert(b);
});
Upvotes: 0
Reputation: 1856
Following code will be helpful to you,
// keyup event fire on all inputs its id starts with mon
$('input[id^="mon"]').keyup(function() {
var $sum = 0;
$('input[id^="mon"]').each(function(){
var $value = this.value;
if($value){
$sum+=parseFloat($value);
}
});
alert($sum);
});
Upvotes: 1
Reputation: 1011
to add events to dynamically created elements, use
var ele = '#mon'+b;
$(document).on('keyup',ele,function(){
console.log('Monday');
})
Upvotes: 0