javascript - 如何获取多个选择框的值并将结果显示在文本框中?

标签 javascript php jquery ajax codeigniter

我有一个包含项目列表的下拉菜单,每个项目都有每个价格。选择商品后,其总价将填充在文本框中。这是我的下拉菜单-

   <select name="treatment[]" class="col-sm-12 country" id="" multiple="multiple">    
       <option value="">--Select--</option>
       <?php foreach($treatment as $treatments) { ?>
         <option value="<?php echo $treatments->treatment_name ?>"><?php echo $treatments->treatment_name ?></option>
       <?php }?>                      
   </select>

我试图使用ajax,但我迷路了。有人可以帮助我吗?提前谢谢。

最佳答案

each item holding each price

如果priceitem 一起存储在同一个表中,您只需添加 data attributes进入option获取更多数据。如果不是更好Joined it在您的 codeigniter Controller 或模型中将所有价格与商品链接在一起。这是我可以向您展示的示例:

假设你有这样的HTML结构:

<select name="treatment[]" class="col-sm-12 country" id="" multiple="multiple">
 // this line of code loop by php
 // see data-price attribute store Price inside
 // later we can referencing this attribute
 <option value="fish" data-price="200">Fish</option>
 <option value="chicken" data-price="500">Chicken</option>
</select>
// place to display total
<input type="text" id="total" /> 

这里 jQuery 代码用于总结所有选定的项目:

$('.country').click(function () {
  var price = 0;
   $('option:selected', $(this)).each(function () {
     //console.log($(this).data('price'));
     // sum price for selected items
     price += $(this).data('price');
  });
  $('#total').val(price);
});

<强> DEMO

已更新

如果您使用内联 javascript,例如 onchange ,然后您需要将其引用发送到您想要调用的函数中,如下所示:

在 HTML 部分更改为: onchange="update_price(this)" ,以及 JS 如下:

function update_price(e) {
                   // ^ add this
 //$('#treatment').on('change',function () { comment this

  var price = 0;                          
  $('option:selected', $(e)).each(function() {
                      // ^ add this
    console.log($(this).data('pricetag'));
    // sum price for selected items
    price += $(this).data('pricetag');

  });
  $('#total').val(price);
//}); comment this
}

关于javascript - 如何获取多个选择框的值并将结果显示在文本框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32198397/

相关文章:

c# - 验证电子邮件而不允许jquery中的空格

javascript - 不应该触发的事件

javascript - 将选项值传递给 php 而不提交表单

php - Ratchet 框架 : needing to click logout link twice

php - 是否可以在不使用列名的情况下更新 MySql 中的值?

javascript - JQuery append 和 Javascript appendChild 在附加元素中带有 document.write

javascript - 表单验证Jquery没有错误

javascript - 环回 IO OAuth 不起作用

javascript - 使用php脚本定期检查LAMP服务器主页时返回奇怪的Javascript

javascript - Braintree-javascript - 收集额外的客户信息?