Home > Mobile >  jQuery using an keyup function in a loop
jQuery using an keyup function in a loop

Time:10-21

Here is the situation,

I have multiple fields with different field names based on the months.

Here are the sample field names:

     <input type="text" name="month-numbers" id="month-revenue-1" /> 
     <input type="text" name="month-numbers" id="month-revenue-2" /> 
     <input type="text" name="month-numbers" id="month-revenue-3" /> 
     ..........
     <input type="text" name="month-numbers" id="month-revenue-12" /> 

In my javascript, I have the actual array created in javascript:

     var actualMonths = [1,2,3,4,5,6,7,8,9,10,11,12];

Now, here is my loop:

      for (i=0;  i < actualMonths.length; i  ) {
           $('input#month-revenue-' month).keyup(function(){
                revenue = $(this).val();
                margin = $('input#month-margin-' month).val();
                value = (margin / 100) * revenue;
                value = value.toLocaleString("en-US");
                $('#month-price-' month).html(value);
           });
      }

It is getting the data from the correct field, however, within the keyup function, it seems to be trying to place the data at the end of the loop. Why is that happening?

My expected result was to have each field calculated differently. For example, month-revenue-1 should be calculating the values.

CodePudding user response:

If you attach the keyup handler function to a parent html element, the same function can handle the event for all children. Use e.target to know which input triggered the event.

$('#months').keyup(function(e) {
  let month = e.target.id.split('-')[2];
  let revenue = $(e.target).val();
  let margin = $('input#month-margin-'   month).val();
  let value = (Number(margin) / 100) * Number(revenue);
  $('#month-price-'   month).html(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="months">
  <input type="text" name="month-numbers" id="month-revenue-1" />
  <input type="text" name="month-margins" id="month-margin-1" />
  <span id="month-price-1"></span>
  <br />
  <input type="text" name="month-numbers" id="month-revenue-2" />
  <input type="text" name="month-margins" id="month-margin-2" />
  <span id="month-price-2"></span>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related