我有一个包含项目列表的下拉菜单,每个项目都有每个价格。选择商品后,其总价将填充在文本框中。这是我的下拉菜单-
<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
如果price
与 item
一起存储在同一个表中,您只需添加 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/