Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Dynamically created html elements with jquery

I am counting the number of inputs on the current document that have value. It works fine, except for when I have dynamically added more inputs. I can't get there values.

For example I may have

<input id="participant-1"/>
<input id="participant-2"/>
...

Dynamically created after button click

<input id="participant-15" />

I'll get the value of each one in a for loop like

for(var i =1 ; i <25; i++)
{
  ...$('input#participant-' + i).val();
}

Now when I run a for loop to check the value of each one of these inputs it only gets the values of the inputs that weren't dynamically created. I have looked at the other questions on here and I still can't see how to apply something like .on() to what I am trying to accomplish.

NEW FOLLOW UP QUESTION ok, now I think this is where I need more clarification concerning how to use the .on.

I have a jsfiddle here: JsFiddle example

where I create new elements and on blur of all text boxes I would like to calculate how many of the elements have value and log it. Now it currently will respond from blur event with elements who were static. It doesn't work for dynamically created elements

like image 651
Abdullah Rasheed Avatar asked Dec 19 '12 03:12

Abdullah Rasheed


1 Answers

Give it a common class:

<input class="textbox" id="participant-1"/>
<input class="textbox" id="participant-2"/>

And get it like:

var values = [];
$('.textbox').each(function(){
    values.push($(this).val());
});
console.log(values)

And to answer the edit:

The Syntax should be : $(container_selector).on(event_type, target_selector, callback)

JSFiddle Demo

$('.name').on('blur', 'input', calculate_total);
like image 181
Akhil Sekharan Avatar answered Sep 29 '22 06:09

Akhil Sekharan