简体   繁体   中英

How to get sum of dropdown list values?

This is my JavaScript function:

<script type="text/javascript">


$(document).ready(function() {
    $('#roomOptions select').change(function() {
        var total = 0;
        $('#roomOptions select').each(function() {

        });(function() {
            total+=parseInt($(this).val());

        });
        $('#roomOptions #roomOptions_total').html(total);
    });
});

This is my php dropdown list code.

<select name="select" id="select">
     <option value="0">Select adults</option>       
       <?php 
       $result = mysql_query("select max_adult from room_category where  room_type = '".$var_value."' ");
       while ($data = mysql_fetch_array($result))
       {
           $adult = $data['max_adult']; 

           for($n=1; $n<=$adult; $n++)
           {


            ?>
           <option value="<?php echo $n ?>"><?php echo $n ?> </option>
      <?php     } ?>

           <?php
           }
         ?>
         </select></td>
  <td align="center">  <select name="select2" id="select2">
     <option value="0">Select children</option>       

    <?php 
       $result1 = mysql_query("select max_child from room_category where  room_type = '".$var_value."' ");
       while ($data1 = mysql_fetch_array($result1))
       {
           $child = $data1['max_child']; 

           for($k=1; $k<=$child; $k++)
           {


            ?>
    <option value="<?php echo $k ?>"><?php echo $k ?> </option>
    <?php     } ?>

    <?php
           }
         ?>
  </select></td>

</tr> <?php } ?>

<tr> 

In this JavaScript function i can get total number of adults and children. I want to get No of adults and No of children separately. I would be very grateful if any one can help me.

You are doing it in the wrong way. Try with -

        var total = 0;
        $('#roomOptions select').each(function() {
              total += parseInt($(this).val());
        });

In your code -

$(document).ready(function() {
    $('#roomOptions select').change(function() {
        var total = 0;
        $('#roomOptions select').each(function() {

            total+=parseInt($(this).val());

        });
        $('#roomOptions #roomOptions_total').html(total);
    });
});

Try this:

$(document).ready(function () {
    $('#roomOptions select').change(function () {
        var total = 0;
        $('#roomOptions option').each(function () {
            total += parseInt($(this).val());
        });
        $('#roomOptions #roomOptions_total').html(total);
    });
});

Use

$('#roomOptions #select').each(function() {});
$('#roomOptions #select2').each(function() {});

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