简体   繁体   English

如何在php的jquery循环内求和框的值

[英]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 这是我的html,我需要对更改时选择字段的值求和

    <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 ) . 例如,如果i值为2表示我想对2个选择字段中选择的值求和(在选择1中选择45,在选择2中选择95,则输出应为140)。 How to get in jquery 如何获取jQuery

PHP is server-side. PHP是服务器端的。 JS is client side. JS是客户端。 You can't use PHP to find the sum at runtime. 您不能使用PHP在运行时查找总和。 Here is an example of how you can do this with jQuery- 这是一个使用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>

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. 注意:您的文件必须是PHP文件才能执行此操作,否则此操作将无效。

Hoped this helped. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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