Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Dynamic input field values are not calculating the with the right value

I am using Codeignator. My HTML output which is correct for me.

enter image description here Now What I am doing is, the user will enter the name of the medication, no of pills and amount so that based on the amount it will calculate the price and display it. Formula is $single_price=$total_amount/$qty_number;

enter image description here

Above image I added medication name="SIPLA", no of pills=3 and amount=30. It will calculate it and display the single price=10.00

Everything is working perfectly til now.

Let's talk about the "ADD" button. If any user wants more then one medication then he/she should click on "ADD" button and it will display the same field as above.

I did the same process, I added a medication name="ZOCON 400", no of pills=4 and amount=60. It calculating and displaying the single price=20.00 which is wrong it should be displayed single price=15.00.

1) Why I am getting single price=20.00 because it's talking no of pills=3 which is added in the first medication. So it's talking the first one quantity. It should talk no of pill=4

2) The calculation of the single price is also displaying in both fields. first one as well as second one. I need only in the second one.

3) How to submit this data in the database?

Hope you understand my issue.

enter image description here

Code View

<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 and 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); 
        }
      });
});

});

Controller

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;}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It also seems you had a bug on the removal/add action. If you had the case where you add 4 items, so

  • 1 (initial)
  • 2,3,4 (dynamically generated)

and then decide to remove the 2. You decrease x by one, witch give you x=3 and the row 1,3,4. If now, you add a new item, you get x+1 and so the collection 1,3,4,4.

To avoid this pattern, It's maybe a good idea to use the current time (at the add execution time) to generate an identifiant to your row.

Since you are working on the HTML contained in a "add_row" div, you can use it as a referent. Instead of using the "n" value received by your increase/decrease click event, you can get the .parents(".add_row") and then select the .find('.single_price') or .find('.total_p_price') easily

Another approche would be to use a "data-" parameter or a class allowing you to identify easily the current row where you are working. I probably use something like that :

<div class="custom_fields" data-time="1540021654"> <!-- current time on the dynamically added row -->
  <input type="text" name="medication_name[]" data-time="1540021654" class="medication_name">
  <span class="value-button" data-time="1540021654" onclick="decreaseValue" value="Decrease Value">-</span>
  <input type="number" data-time="1540021654" class="qty_member" value="0" name="qty_member[]" />
  <span class="value-button" data-time="1540021654" class="increase_name" onclick="increaseValue">+</span>
  <br />
  <input type="text" class="form_control" data-time="1540021654" name="single_price[]" class="single_price"  />    
  <input type="text" class="form_control" data-time="1540021654" name="total_p_price[]" class="total_p_price" /> 
  <div class="btn_row remove_field"> 
  <span> - </span> Remove  </div>
</div>

(I have simplify a little the html for easily find my changes) With this and jquery, you can find instant all the data you want and update it $('.single_price data[time="1540021654"]').val() will give you this result and only it.

Another mistake is, you are generating buttons with an id static, like <span class="value-button" id="increase" onclick="increaseValue('+ x +')" value="Increase Value"> This is a mistakes because id should be Unique.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...