如何将两个动态生成的字段(输入和跨度)的值相乘

问题描述 投票:0回答:1

我有一个select和一个由JavaScript生成的input。到目前为止,这很好用,但是现在的问题是我想将在input字段中输入的任何值乘以25。

例如,如果我在输入字段中输入2,它将自动在50中显示span。如果我继续动态添加更多输入字段,则新的span和新的input字段仍应具有相同的功能。

$('.addRow').on('click', function() {
  i++;
  addRow();
});

function addRow() {
  var tr = '<tr class="dynamic-added">' +
    '<td>' +
    '<select ng-model="marketers" id="marketers" class="form-control marketers" name="marketers[]">' +
    '<option value="">Select Marketer </option>	 @foreach($marketers as $data)' +
    '<option value="{{$data->first_name}}">{{$data->first_name}} {{ $data->last_name }}</option> @endforeach' +
    '</select>' +
    '</td>' +
    '<td><input type="text" name="target[]" id="target2" class="form-control target" /> </td>' +
    '<td><span id="result">0</span> </td>' +
    '<td> <a href="#" class="btn btn-danger remove">- </a> </td>' +

    '</tr>';
  $('tbody').append(tr);
};
<td>
  <input type="text" name="target[]" id="target2" class="form-control target" id="target">
</td>
<td><span id="result1" class="margin-left-1 font-weight-400 example-title">15</span> </td>
<td> <a href="#" class="btn btn-danger remove">- </a> </td>


I have tried the following code..but the problem is it works for the first dynamic field..but the subsequent one doesnt work.
 

<script>
                                      
        function add() {
        document.getElementById("products").disabled = false;
        var value1 = document.getElementById('target').value || 0;

        document.getElementById('sum1').innerHTML = parseInt(value1 * 26);


        var value2 = document.getElementById('target2').value || 0; 
        document.getElementById('result1').innerHTML = parseInt(value2 * 26);
        
        }

        </script>
javascript jquery
1个回答
0
投票

更好的JS实践是:

const eProduct = document.getElementById("products")
    , eTarget  = document.getElementById('target')
    , eTarget2 = document.getElementById('target2')  
    , eSum1    = document.getElementById('sum1')
    , eResult1 = document.getElementById("result1")
    , coef     = 26



function add()
{
  eProduct.disabled = false;
  eSum1.textContent    = ( parseInt(eTarget.value)  || 0 ) * coef;
  eResult1.textContent = ( parseInt(eTarget2.value) || 0 ) * coef;
}
© www.soinside.com 2019 - 2024. All rights reserved.