vellai durai
vellai durai

Reputation: 1011

How to sum the select box value inside loop in jquery in php

Here is my html, I need to sum the value of select fields on change

    <for i=0;i<3,i++) {

    <select id="options_<?php echo $i ?>">

       <option value="25">RS 25</option>
        <option value="30">Rs 30</option>
        <option value="45">Rs 45</option>
         <option value="95">Rs 95</option>
     </select>

       }

   <p id=""sum_of_select> </p>

For example if i value is 2 means i want to sum the value selected in 2 select fields (45 is selected in select 1 and 95 selected in select 2 the output should be 140 ) . How to get in jquery

Upvotes: 1

Views: 336

Answers (2)

user6061856
user6061856

Reputation:

first off, I recommend before asking a question on here, make sure you debug and check before submitting a question.

What your code looks like:


for i=0;i<3,i++) {
  <select id="options_<?php echo $i ?>">
   <option value="25">RS 25</option>
   <option value="30">Rs 30</option>
   <option value="45">Rs 45</option>
   <option value="95">Rs 95</option>
  </select>
}
<p id=""sum_of_select> </p>

Now to be honest, your code is a bit confusing. But I'll see if I can sum up something for you.

What your code should look like:


<?php
// start the loop
for i=0;i<3,i++) {
?>

  <select id="options_<?php echo $i ?>">
    <option value="25">RS 25</option>
    <option value="30">Rs 30</option>
    <option value="45">Rs 45</option>
    <option value="95">Rs 95</option>
  </select>

<?php
} // end the loop
?>

<!-- here will go your summary -->
<p id="sum_of_select"></p>

<script>
// and to use your PHP variable in Jquery or Javascript:
var yourVarName = <?php echo $i; ?>;
</script>

NOTE: Your file must be a PHP file to do this, else this won't work.

Hoped this helped.

Upvotes: 1

micah
micah

Reputation: 8096

PHP is server-side. JS is client side. You can't use PHP to find the sum at runtime. Here is an example of how you can do this with jQuery-

<for i=0;i<3,i++) {

<select class="sum-selector" id="options_<?php echo $i ?>">

   <option value="25">RS 25</option>
    <option value="30">Rs 30</option>
    <option value="45">Rs 45</option>
     <option value="95">Rs 95</option>
 </select>

   }

<p id=""sum_of_select> </p>

<script>
$('.sum-selector').change(getSum);

function getSum() {
  var sum = 0;
  $('.sum-selector').each(function(select) {
    if(select.value) {
      sum += parseInt(select.value);
    }
  });

  alert('sum is: ' + sum);
}
</script>

Upvotes: 1

Related Questions