os valores del campo de entrada dinámico no se calculan con el valor correct

Estoy usando Codeignator. Mi salida HTML que es correcta para mí.

Ahora lo que estoy haciendo es que el usuario ingresará el nombre del medicamento, no las píldoras y la cantidad, de modo que, en función de la cantidad, calculará el precio y lo mostrará. La fórmula es$single_price=$total_amount/$qty_number;

Sobre la imagen agreguémedication name="SIPLA", no of pills=3 yamount=30. Lo calculará y mostrará elsingle price=10.00

Todo funciona perfectamente hasta ahora.

Hablemos del botón "AGREGAR". Si algún usuario desea más de un medicamento, debe hacer clic en el botón "AGREGAR" y se mostrará el mismo campo que el anterior.

Hice el mismo proceso, agregué unmedication name="ZOCON 400", no of pills=4 yamount=60. Calcula y muestra lasingle price=20.00 que está mal, debería mostrarsesingle price=15.00.

1) Por qué obtengo un precio único = 20.00 porque no se habla de píldoras = 3, que se agrega en el primer medicamento. Entonces se trata de la primera cantidad. Debería hablar no de píldora = 4

2) El cálculo del precio único también se muestra en ambos campos. tanto el primero como el segundo. Solo necesito en el segundo.

3) ¿Cómo enviar estos datos en la base de datos?

Espero que entiendas mi problema.

Códig Ve

<div class="add_row">
    <input type="text" name="medication_name[]" id="medication_name" class="form_control text_cap" placeholder="medication_name">

    <span class="value_button" id="decrease" onclick="decreaseValue(1)" value="Decrease Value">-</span>
    <input type="number" id="number1" class="qty_number form_control"  name="qty_number[]" value="0" class="form_control"/>
    <span class="value_button" id="increase" onclick="increaseValue(1)" value="Increase Value">+</span>

    <input type="text" class="form_control" name="single_price[]"  id="single_price"  placeholder="single price" />

    <input type="text" class="form_control" name="total_p_price[]" id="total_p_price" placeholder="total price" />

    <div class="btn_row add_row_click"> <span> +  </span> Add </div>

  </div>

Ajax y Js

function increaseValue(n) {
  var value = parseInt(document.getElementById('number' + n).value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number' + n).value = value;
}

function decreaseValue(n) {
  var value = parseInt(document.getElementById('number' + n).value, 10);
  value = isNaN(value) ? 0 : value;
  value < 1 ? value = 1 : '';
  value--;
  document.getElementById('number' + n).value = value;
}

  $(document).ready(function() {
    var max_fields      = 20; //maximum input boxes allowed
    var wrapper         = $(".add_row"); //Fields wrapper
    var add_button      = $(".add_row_click"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment

                $(wrapper).append('<div class="custom_fields"><input type="text" name="medication_name[]" id="medication_name'+ x +'" class="form_control text_cap" placeholder="medication_name"><span class="value-button" id="decrease" onclick="decreaseValue('+ x +')" value="Decrease Value">-</span><input type="number" id="number'+ x +'" value="0" name="qty_member[]" /><span class="value-button" id="increase" onclick="increaseValue('+ x +')" value="Increase Value">+</span><br /><input type="text" class="form_control" name="single_price[]"  id="single_price'+ x +'"  placeholder="single price" />    <input type="text" class="form_control" name="total_p_price[]" id="total_p_price'+ x +'" placeholder="total price" /> <div class="btn_row remove_field"> <span> - </span> Remove  </div></div>');
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); 
        //$(this).parent('custom_fields').remove();
                $(this).closest('.custom_fields').remove();

         x--;
    })
$("body").on('keyup', 'input[id^=total_p_price]', function() {
  //$('input[id^=single_price]').prop('disabled', true);
    var  total_p_price= $(this).val();
    var qty_number = $('input[id^=number]').val();
    $.ajax({
        type  : "POST",
        url: baseUrl + "/Customer_control/calculate_total_p_price",
        data: {total_p_price: total_p_price,qty_number:qty_number},
        cache : false,
        success: function(html) {
          //alert(html);
          $('input[id^=single_price]').val(html); 
        }
      });
});

});

Controlado

public function calculate_total_p_price(){
  $total_p_price=$this->input->post('total_p_price');
  $qty_number=$this->input->post('qty_number');

  $single_price=$this->Customer_model->calculate_total_p_price($total_p_price,$qty_number);

  echo $single_price;
}

Model

public function calculate_total_p_price($total_p_price,$qty_number){

 // print_r($total_p_price);
if(empty($qty_number) || ($qty_number == 0)){
return 0;
}
elseif(empty($total_p_price) || ($total_p_price == 0)){
return 0;
}
elseif(!empty($total_p_price) && (!empty($qty_number) || ($qty_number>0))){
  $single_price=$total_p_price/$qty_number;
return number_format((float)$single_price, 2, '.', '');
}
else{return 0;}

}

Respuestas a la pregunta(2)

Su respuesta a la pregunta