vellai durai vellai durai - 6 months ago 34
Javascript Question

I need to sum the value of select box value inside jquery

I need to sum the select box value inside loop in jquery ,

<?php

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>

<?php } ?>

<p id="sum_of_select"> </p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

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


Here on change the value is coming as 0 on alert i need to get the sum value of the three select box value , for example in first select box if i select 25 second 30 third 45 the output should be 100

Answer

Use this to get the selected value

$('.sum-selector').each(function(i) {
     alert($(this).find('option:selected').val());
});

Here is your code :

<?php 

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>
<?php  } ?>

<p id="sum_of_select"> </p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$('.sum-selector').change(getSum);
function getSum() 
{
  var sum = 0;
  $('.sum-selector').each(function(i) {
    if($(this).find('option:selected').val()) {
      sum += parseInt($(this).find('option:selected').val());
      alert(sum)
    }
  });
  alert('sum is: ' + sum);
}
</script>
Comments