Soyong
Soyong

Reputation: 188

JQuery: on input event on dynamically created inputfields

I am trying to add all values of a tablerow together. This as soon as someone enters a value into an inputfield. table:

<table>
  <thead>
    <tr>
    <th>
      Title
    </th>
    <th>
      Input
    </th>
    <th>
      Total
    </th>
    </tr>
  </thead>
  <tbody>
    <!-- Dynamially Generated Table Columns -->
    <tr>
      <td>Example</td>
      <td><input type="text" class="inputField" /></td>
      <td>Total: x</td>
    </tr>
  </tbody>
</table>

The only solution I've found so far is:

$(document).on('input', '.inputField', function(){ /* Do something */});

The Problem here is, that this line reads all input fields in the document, but I only want those of one row. Also if I'd change it to 'tbody' it would just read all fields of the tablebody.

So what I am looking for is a way to just select those inputs of one single tablerow, so I can take those values and add them together.

Thanks a lot for the help!

Upvotes: 3

Views: 232

Answers (2)

ADyson
ADyson

Reputation: 61839

This answer is assuming you mean there will be multiple <input> elements within the same <tr> in reality, and you want the total entered into all of these.

You can still use that event. But the key thing is within that event, to only select the inputs which fall within the current row. Since you know which element the event occurred on, you can use that information to find out its parent row, and therefore discover all the other input elements within that row. Something like this:

$(document).on('input', '.inputField', function(){ 
  var parentRow = $(this).parents("tr").first();
  var inputs = parentRow.find('input[type="text"]');
  var total = 0;
  inputs.each(function(){
    total += parseInt(this.value);
  });
  alert (total);
});

Bear in mind above I haven't included any validation of whether the input into the field is actually a valid integer or anything like that. It's worth considering that.

Further, if you want to write into the nearby <td> probably best to give that <td> a class e.g. class="total", then you can easily update it. So instead of

alert(total);

in the above example, you could write

parentRow.find(".total").text(total);

Upvotes: 2

fernando
fernando

Reputation: 822

you can use .change for that

$('input[name=myInput]').change(function() { ... });

Upvotes: 0

Related Questions