根据用户对数组的选择计算交换价格

calculate exchange price depending on user choice from array

本文关键字:计算 交换 选择 用户 数组      更新时间:2023-09-26

我从数据库中获取php数据,使用json_encode转换为js数组。所有的好。但是在数组中有4个索引,我试图使用特定的索引,这取决于用户在html中的选择。我想用jquery/js来做这个。查看代码以获得更深入的解释!

jsfiddle: EDIT:更新jsfiddle语法

https://jsfiddle.net/Lqd9vjnh/2/

html

    <label for="amount"><h3><i class="fa fa-database">&nbsp;Amount</i></h3></label>
                                    <input type="text" class="form-control" id="amount" name="gpamount" required>
<select class="form-control" name="goldtype" style="margin-top:30px; width: 70%;" id="goldtype">
                                            <option value="x">Val1</option>
                                            <option value="y">Val2</option>
                                            <option value="z">Val3</option>
                                        </select>
                        <label for="price"><h3><i class="fa fa-database">&nbsp;Price</i></h3></label>
                                        <input type="text" class="form-control" id="price" >
js/jquery

var amount = $('#amount'),
  goldtype = $('#goldtype'),
  exchange = ["0.5", "1.5", "3.5", "$"] //I will set static array here. //<?php echo json_encode($exchangeRates);?>,
price = $('#price');
var choice = goldtype.val();
if (choice = x) {
  goldtype = exchange[0];
}
if (choice = y) {
  goldtype = exchange[1];
}
if (choice = z) {
  goldtype = exchange[2];
}
amount.add(goldtype).on('change input', function() {
  price.val(function() {
    return (amount.val() * goldtype.val().toFixed(2) + '')
  })
});

请在寻求帮助时尽量更明确,因为这不仅节省了别人的时间,而且还降低了你的问题被否决和驳回的机会。
我想到了一些东西,我认为应该是你问题的答案,如果不是,请说出来。

下面的代码找出选择了哪个选项,并将其数量乘以相同索引的交换值。

goldtype.change(function () {
    var exchangeIndex = $("select[name='goldtype'] option:selected").index()
    price.val(amount.val() * exchange[exchangeIndex]);
})

我还加入了一段代码,当你第一次单击数组时,它会根据交换数组改变你的选项(希望有帮助)。

你可以在这里找到codepen