简体   繁体   中英

Javascript sum fields in many select and put this value in a input

I'm using this script for recovering some data from my database MYSQL and it works pretty fine. My page is in PHP.

 <script type = "text/javascript">
$(document).ready(function() {
    $("select#product1").on("change", function() {
        var id = this.value;
        $.ajax({
            url: "ajax.php",
            method: "post",
            data: "id=" + id,
            success: function(response) {
                var datashow = JSON.parse(response);
                price1 = datashow[0].price;
                time1 = datashow[0].time;
                $("input#totalprice").val(price1);
                $("input#totaltime").val(time1);
            }
        });
    });
}); </script>

My HTML is like this:

<select id="product1" name="product1">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product1" name="product2">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product1" name="product3">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product1" name="product4">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product1" name="product5">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>


<input id="totalprice" type="text" name="totalprice" />
<input id="totaltime" type="text" name="totaltime" />

In this way I'm able to fill my 2 different input: totaltime and totalprice , with the value recovered with my ajax.php file.

The problem is that I have 5 different select, not only product1 but also product2, product3, product4 and product5.

I need my 2 input, totalprice and totaltime, to be automatically filled in with the sum of the values recovered from my ajax, for each select. It means I will have (or maybe not, they are not mandatory fields) price2 and time2, price3 and time3...

To be more clear: I have 5 different select fields, with dynamic products. Each of those products have a price and a time stored in mysql, that i recover through the json. I need to store the totalprice (sum of each of those) and the totaltime into an input.

Any idea to how I can solve this?

Thank you :)

When you add value into text box before that check the value of this box

var value1 =$("input#totalprice").val();
var totalPrice = parseInt(price1)+parseInt(value1 );
$("input#totalprice").val(totalPrice);

Try this way

  var price = parseInt($("input#totalprice").val());
  var time= parseInt($("input#totaltime").val());

  $("input#totalprice").val(price+price1);
  $("input#totaltime").val(time+time1);

If I am understanding you correctly you want to loop through the json data and add each price to a total variable and then store it in the totalprice input. I am assuming the html markup and you will have to adjust your id and class names to match. Now of course the values of each input will be added dynamically from your database during your AJAX call and it looks like you have already figured that part out. Just make sure you put the JavaScript code inside of your Ajax success function.

Live Preview

HTML:

<select class="product" name="product1">
<option value="" selected="selected">-</option>
<option value='20'>20</option>
</select>
<select class="product" name="product2">
    <option value="" selected="selected">-</option>
    <option value='30'>30</option>
</select>
<select class="product" name="product3">
    <option value="" selected="selected">-</option>
    <option value='40'>40</option>
</select>
<select class="product" name="product4">
    <option value="" selected="selected">-</option>
    <option value='15'>15</option>
</select>
<select class="product" name="product5">
    <option value="" selected="selected">-</option>
    <option value='22'>22</option>
</select>    

<input id="totalprice" type="text" name="totalprice" />
<input id="totaltime" type="text" name="totaltime" />

JavaScript/JQuery(Placed at the end of your Ajax Success Function):

var total = 0;

//I am using this to simulate your ajax function since I don't have access to your database
$("select").on("change", function() {

  //Place the following code at the bottom of your ajax success function

  //clear out the total to
  //prevent old prices from being added to the total
  total = 0;

  $(".product").each(function() {

    //if the value is not an empty string
    if ($(this).val() !== "") {

      //add the price to the total
      total += parseInt($(this).val());

    }

  }); //end each function

  //update the total
  $("#totalprice").val(total);

}); //end on change event

Update Optional Solution: Based on your comments I belive you will want to do something like following. Now keep in mind you will have to change the url of your ajax call and switch the value of datashow variable back to what you had it. I had to change it to use a json file to simulate your call to the database.

HTML:

    <div id="products">
<select id="product1" name="product1">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product2" name="product2">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product3" name="product3">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product4" name="product4">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
<select id="product5" name="product5">
    <option value="" selected="selected">-</option>
    <option value='17'>Product1</option>
</select>
        </div>

<input id="totalprice" type="text" name="totalprice" />
<input id="totaltime" type="text" name="totaltime" />

JavaScript:

$(document).ready(function() {
    $("#products select").on("change", function() {
        var id = this.value;
        $.ajax({
            url: "ajax.json",
            method: "get",
            data: "id=" + id,
            success: function(response) {               

         //initialize totalPrice to 0 if doesn't contain a value
         var totalPrice = $("#totalprice").val() !== "" ? parseInt($("#totalprice").val()): 0;

                var datashow =  response;//JSON.parse(response);
                var price1 = parseInt(datashow[0].price);
                var time1 = datashow[0].time;


                //add the total price
                $("input#totalprice").val(totalPrice + price1);

                //Do something similar for time, I don't how you plan on parsing this?
                $("input#totaltime").val(time1);


            }
        });
    });
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM