sum of price-data according to the selection from multi select dropdown

as per the selection i want total of data-price to be displayed in totalamount input box

 <HTML>
   <body>
<form name="myForm" action="insert.php" onsubmit="return validateForm()" method="post" id="myForm" style="width=90%" enctype="multipart/form-data" required>
<label>Test Name:</label>
     <select id="framework" name="framework[]" multiple class="form-control" >
<option value="HDL Cholesterol" data-price="180">HDL Cholesterol</option>
<option value="Total Cholesterol" data-price=180180180>Total Cholesterol</option>
<option value="Triglycerides (TG)" data-price=180285180>Triglycerides (TG)</option>
<option value="Sugar (Glucose) Fasting (FBS)" data-price=28570285>Sugar (Glucose) Fasting (FBS)</option>
<option value="Sugar (Glucose) Post Prandial (PPBS)" data-price=707070>Sugar (Glucose) Post Prandial (PPBS)</option>
<option value="Sugar (Glucose) Random (RBS)" data-price=707070>Sugar (Glucose) Random (RBS)</option>
<option value="Reticulocyte Count" data-price=7055070>Reticulocyte Count</option>
<option value="Total Thyroxine (T4)" data-price=550198550>Total Thyroxine (T4)</option>
<option value="Total Triiodothyronine (T3)" data-price=198198198>Total Triiodothyronine (T3)</option>
<option value="TSH (Thyroid Stimulating Hormone)" data-price=198240198>TSH (Thyroid Stimulating Hormone)</option>
<option value="Alkaline Phosphatase (ALP)" data-price=240210240>Alkaline Phosphatase (ALP)</option>
<option value="Aspartate Aminotransferase (SGOT )" data-price=210190210>Aspartate Aminotransferase (SGOT )</option>
<option value="Bilirubin Total" data-price=190130190>Bilirubin Total</option>
<option value="Calcium" data-price=130176130>Calcium</option>
<option value="Iron" data-price=176380176>Iron</option>
</select>
<td><label>Total Amount:</label><input type="number" name="totalamount">
</body>
</html>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A solution in 2 flavors. The reduce can be used for either method of course, but in the jQuery way, I tried to stick with jQuery methods.

VanillaJS

You can just tally it up with an array.reduce() function as it’s being changed using a change event listener. Keep the variable global so you can reference it elsewhere (like in form.submit).

This line, explained:

totalVal = [...e.target.querySelectorAll('option:checked')] // get the HTML collection of selected option elements and convert that into an iterable array using the  [...] spread syntax
            .reduce((b, a) => // b is the accumulating value, a is the current iterating element
                (b + +a.dataset.price) // convert the price data-attribute to a number using the shorthand +
             , 0); // b starts out as zero and we add to it
let totalVal = 0;
window.addEventListener('load', () => {
  document.querySelector('#framework').addEventListener('change', e => {
    totalVal = [...e.target.querySelectorAll('option:checked')].reduce((b, a) => (b + +a.dataset.price), 0);
    document.querySelector('[name=totalamount]').value = totalVal
  })
})
<form name="myForm" action="insert.php" onsubmit="return validateForm()" method="post" id="myForm" style="width=90%" enctype="multipart/form-data" required>
  <label>Test Name:</label>
  <select id="framework" name="framework[]" multiple class="form-control">
    <option value="HDL Cholesterol" data-id="1" data-price="180">HDL Cholesterol</option>
    <option value="Total Cholesterol" data-id="2" data-price="180180180">Total Cholesterol</option>
    <option value="Triglycerides (TG)" data-id="3" data-price="180285180">Triglycerides (TG)</option>
    <option value="Sugar (Glucose) Fasting (FBS)" data-id="4" data-price="28570285">Sugar (Glucose) Fasting (FBS)</option>
    <option value="Sugar (Glucose) Post Prandial (PPBS)" data-id="5" data-price="707070">Sugar (Glucose) Post Prandial (PPBS)</option>
    <option value="Sugar (Glucose) Random (RBS)" data-id="6" data-price="707070">Sugar (Glucose) Random (RBS)</option>
    <option value="Reticulocyte Count" data-id="7" data-price="7055070">Reticulocyte Count</option>
    <option value="Total Thyroxine (T4)" data-id="8" data-price="550198550">Total Thyroxine (T4)</option>
    <option value="Total Triiodothyronine (T3)" data-id="9" data-price="198198198">Total Triiodothyronine (T3)</option>
    <option value="TSH (Thyroid Stimulating Hormone)" data-id="10" data-price="198240198">TSH (Thyroid Stimulating Hormone)</option>
    <option value="Alkaline Phosphatase (ALP)" data-id="11" data-price="240210240">Alkaline Phosphatase (ALP)</option>
    <option value="Aspartate Aminotransferase (SGOT )" data-id="12" data-price="210190210">Aspartate Aminotransferase (SGOT )</option>
    <option value="Bilirubin Total" data-id="13" data-price="190130190">Bilirubin Total</option>
    <option value="Calcium" data-id="14" data-price="130176130">Calcium</option>
    <option value="Iron" data-id="15" data-price="176380176">Iron</option>
  </select>
  <hr>
  <label>Total Amount:</label><input type="number" name="totalamount">
</form>

The jQuery Way

let total = 0;
let code = [];
$('#framework').on('change', function() {
  total = 0;
  code = [];
  $(this).find('option:selected').each(function() {
    total += +$(this).data('price');
    code.push($(this).data('id'));
  })
  $('#totalamount').val(total);
  $('#testcode').val(code.join(", "));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="myForm" action="insert.php" onsubmit="return validateForm()" method="post" id="myForm" style="width=90%" enctype="multipart/form-data" required>
  <label>Test Name:</label>
  <select id="framework" name="framework[]" multiple class="form-control">
    <option value="HDL Cholesterol" data-id="1" data-price="180">HDL Cholesterol</option>
    <option value="Total Cholesterol" data-id="2" data-price="180180180">Total Cholesterol</option>
    <option value="Triglycerides (TG)" data-id="3" data-price="180285180">Triglycerides (TG)</option>
    <option value="Sugar (Glucose) Fasting (FBS)" data-id="4" data-price="28570285">Sugar (Glucose) Fasting (FBS)</option>
    <option value="Sugar (Glucose) Post Prandial (PPBS)" data-id="5" data-price="707070">Sugar (Glucose) Post Prandial (PPBS)</option>
    <option value="Sugar (Glucose) Random (RBS)" data-id="6" data-price="707070">Sugar (Glucose) Random (RBS)</option>
    <option value="Reticulocyte Count" data-id="7" data-price="7055070">Reticulocyte Count</option>
    <option value="Total Thyroxine (T4)" data-id="8" data-price="550198550">Total Thyroxine (T4)</option>
    <option value="Total Triiodothyronine (T3)" data-id="9" data-price="198198198">Total Triiodothyronine (T3)</option>
    <option value="TSH (Thyroid Stimulating Hormone)" data-id="10" data-price="198240198">TSH (Thyroid Stimulating Hormone)</option>
    <option value="Alkaline Phosphatase (ALP)" data-id="11" data-price="240210240">Alkaline Phosphatase (ALP)</option>
    <option value="Aspartate Aminotransferase (SGOT )" data-id="12" data-price="210190210">Aspartate Aminotransferase (SGOT )</option>
    <option value="Bilirubin Total" data-id="13" data-price="190130190">Bilirubin Total</option>
    <option value="Calcium" data-id="14" data-price="130176130">Calcium</option>
    <option value="Iron" data-id="15" data-price="176380176">Iron</option>
  </select>
  <hr>
  <label>Test Code:</label><input type="text" id="testcode" name="testcode">

  <label>Total Amount:</label><input type="number" id="totalamount" name="totalamount">

</form>

Method 2

i am using below function can you please he

on deselecting dropdown option, value remains with no changes
function is to get comma separated testcode to testcode inputbox and totalamount to totalamoun text box 
        <html>`enter code here`
    <body>
          // query to fetch data from database
        $data="";
        $query = "SELECT testcode,testname,mrp FROM pricelist";
        $resultSet = mysqli_query($conn, $query);
        if ($resultSet)
        {
          while($row = mysqli_fetch_array($resultSet)) {
            $data .="<option value='".$row['testname']."' data-price='".$row['mrp']."' data-id='".$row['testcode']."'>".$row['testname']."</option>";
          }
        }
        //form 
        <div class="form-group1">
        <label>Test Name:</label>
             <select id="framework" name="framework[]" multiple class="form-control" >
                  <?php echo $data; ?>
             </select>
            </div>
          </td>    
          <td><label>Test Code:</label><input type="text" id="testcode" name="testcode"></td>    
        <tr class="line_items">    
          <td><label>Total Amount:</label><input type="number" id="totalamount" name="totalamount">
        //jquery function
        <script>
        var total=0;
        var code="";
        $('#framework').on('change', function(){
          var mPrice = $(this).find('option:selected').data('price');
          var mCode = $(this).find('option:selected:last').data('id');
          if (mPrice != null){
            total+=mPrice;
            code +=mCode+',';
            $('#totalamount').val(total);
            $('#testcode').val(code);
          } else {
            
          }
        });
    </body>
        </html>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x