dom - Jquery read value of dynamic input field -


i looking way read value of dynamically created input field , average of them. i've got tablerow multiple inputs, , want add values of inputs , show them @ end of row.

what got far:

html (i generating such rows in table):

<tr> <td><input type='number' class='userinput' name='userinput'></td> <td><input type='number' class='userinput' name='userinput'></td> <td><input type='number' class='userinput' name='userinput'></td> <td class='avg'>x</td> <!-- average --> </tr> 

my jquery code looks this:

$(document).on('input', '.userinput', function () { var parentrow = $(this).parents('td'); var inputs = parentrow.children('input'); var avgtext = $(this).parents('tr').find('.avg'); var avg = 0;     inputs.each(function () { avg += parseint(this.value); }); avg /= 3; avgtext.text(avg); }); 

my problem code is, doesnt update total, overwrites when write second inputfield. looking for, way update average.

you're not selecting elements find average value.

these lines problem:

var parentrow = $(this).parents('td'); var inputs = parentrow.children('input'); 

the first line selects td above chosen input. therefore child input that's been changed. other inputs ignored. divide single value 3, meaning final average wrong.

this example correct - go way <tr>, , use .find() inputs within <tr> (can't use children because goes down 1 level, you'd <td>s.

also i've made more flexible dividing number of inputs, rather hard-coded value. if add more inputs row it'll automatically average well.

$(document).on('input', '.userinput', function () {     var parentrow = $(this).parents('tr');     var inputs = parentrow.find('input');     var avgtext = parentrow.find('.avg');     var avg = 0;         inputs.each(function () {         avg += parseint(this.value);     });     avg /= inputs.length;     avgtext.text(avg); }); 

Comments