我可以根据用户表单输入更改动态javascript变量吗?

时间:2014-06-27 20:56:17

标签: javascript php jquery html html5

我的问题是,是否有办法根据用户在输入字段中输入的名称更改动态价格计算。

我的代码非常适合在html表单中计算动态价格。这是代码:

使用此输入:

<input class="typeahead" type="text" placeholder="Amount" name="Amount"/>

我的Javascript然后计算价格:

jQuery("input[name='Amount']").change(function () {
if (isNaN(parseFloat(this.value)) || !isFinite(this.value)) {
    jQuery(this).val('');
    return false;
}
var calc = parseFloat(this.value) * 0.95;
jQuery(this).parents("form").find("input[name='price']").val(calc);
});

这本身就很棒。它按0.95计算金额,然后将该值指定为价格。

如果我将其添加到表单中:

<input class="stores typeahead" type="text" placeholder="Stores" name="name"/>

我可以在这里做些什么,以便能够根据商店名称计算不同价格的价格。例如,如果有人进入麦当劳,我希望它以0.90计算。如果有人进入Target,我希望它以.92计算。之前的javascript无法实现这一点,因为它会计算.95处的所有内容,而不是根据输入的商店进行更改。

我更喜欢用javascript完成这个,因为我对php不是很熟练。

1 个答案:

答案 0 :(得分:0)

您可以为此创建一个Javascript对象。

var stores = {
     "McDonalds" : .90,
     "Target" : .92,
}
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
console.log(stores[storeName]); //Output the store cost to console.

虽然我认为jQuery查找功能值得怀疑。我确定有更好的方法来选择该文本框。但这是您正在寻找的一般概念。