Как сделать эту функцию более обобщенной c? - PullRequest
0 голосов
/ 25 января 2020

У меня есть небольшая функция jQuery, вычисляющая некоторые входные данные. Я хотел бы иметь возможность сделать это более обобщенным c, чтобы мне не пришлось повторять этот код.

jQuery(document).ready(function(){
    update_amounts();
    jQuery('.list_item_9 input:not([readonly])').change(function() {
        update_amounts();
    });
});

function update_amounts() {
    var sum = 0;
    jQuery('.list_item_9 input:not([readonly])').each(function() {
        sum += Number(jQuery(this).val());
    });
    jQuery('.list_item_9 .gfield_list_184_cell5 input').val(sum);
}

HTML для этого выглядит следующим образом:

<tr class="gfield_list_group list_item_9">
    <td class="gfield_list_cell">
        <input type="text" name="FIELDLABEL" value="" readonly="">
    </td>
    <td class="gfield_list_cell">
        <input type="text" name="TWO" value="">
    </td>
    <td class="gfield_list_cell">
        <input type="text" name="THREE" value="">
    </td>
    <td class="gfield_list_cell">
        <input type="text" name="FOUR" value="">
    </td>
    <td class="gfield_list_cell gfield_list_184_cell5">
        <input type="text" name="TOTAL" value="0" readonly="">
    </td>
</tr>

Я пробовал несколько итераций этого, но я не могу понять, как нацелить функцию на основании того, что изменилось.

Ответы [ 2 ]

1 голос
/ 25 января 2020

Этот код должен делать то, что вы хотите. Каждый раз, когда ввод изменяется, он находит родительский элемент класса gfield_list_group, а затем суммирует все входные данные, не предназначенные только для чтения, и записывает общую сумму на вход с помощью name="TOTAL" (вы можете изменить это на спецификатор класса, например glist_total_cell). Для инициализации существует подпрограмма update_all_amounts, которая суммирует входные данные по всем gfield_list_group элементам.

jQuery(document).ready(function() {
  update_all_amounts();
  jQuery('.gfield_list_group input:not([readonly])').change(function() {
    update_amounts(jQuery(this));
  });
});

function update_amounts(inp) {
  var sum = 0;
  var parent = inp.closest('.gfield_list_group');
  parent.find('input:not([readonly])').each(function() {
    sum += Number(jQuery(this).val());
  });
  parent.find('input[name="TOTAL"]').val(sum);
}

function update_all_amounts() {
  jQuery('.gfield_list_group').each(function() {
    update_amounts(jQuery(this).find('input:not([readonly])').first());
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr class="gfield_list_group list_item_9">
    <td class="gfield_list_cell">
      <input type="text" name="FIELDLABEL" value="row 9" readonly="">
    </td>
    <td class="gfield_list_cell">
      <input type="text" name="TWO" value="">
    </td>
    <td class="gfield_list_cell">
      <input type="text" name="THREE" value="6">
    </td>
    <td class="gfield_list_cell">
      <input type="text" name="FOUR" value="">
    </td>
    <td class="gfield_list_cell gfield_list_184_cell5">
      <input type="text" name="TOTAL" value="0" readonly="">
    </td>
  </tr>
  <tr class="gfield_list_group list_item_10">
    <td class="gfield_list_cell">
      <input type="text" name="FIELDLABEL" value="row 10" readonly="">
    </td>
    <td class="gfield_list_cell">
      <input type="text" name="TWO" value="4">
    </td>
    <td class="gfield_list_cell">
      <input type="text" name="THREE" value="">
    </td>
    <td class="gfield_list_cell">
      <input type="text" name="FOUR" value="">
    </td>
    <td class="gfield_list_cell gfield_list_184_cell5">
      <input type="text" name="TOTAL" value="0" readonly="">
    </td>
  </tr>
</table>
0 голосов
/ 25 января 2020

Демонстрация ниже очень обобщенная c - без идентификаторов, классов или селекторов атрибутов - используются только tagNames.

  • обернуть все в <form> и делегировать " введите для него событие "или" change ".
  • измените type из <input> на number.
  • не забудьте преобразовать каждое значение ввода в действительное число перед вычислениями .
  • не используйте <input readonly>, вместо этого используйте <output></ouput>

Демо

Подробности прокомментированы в демо

// Delegate the input event to the <form>
$('form').on('input', function(e) {
  // Declare sum at 0
  var sum = 0;
  // On each <input>
  $(this).find('input').each(function() {
    // Convert the value of each input and add it to sum
    sum += Number($(this).val());
  });
  // Assign sum to the last <output>
  $('output:last').val(sum);
});
form {
  margin: 50px auto
}
<form>
  <table>
    <tr>
      <td>
        <output>Name</output>
      </td>
      <td>
        <input type="number" value='0'>
      </td>
      <td>
        <input type="number" value='0'>
      </td>
      <td>
        <input type="number" value='0'>
      </td>
      <td>
        <output>0</output>
      </td>
    </tr>
  </table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
...