如何让这两个javascript代码一起工作?

时间:2014-06-27 22:26:43

标签: javascript jquery

我使用html制作了一个表单。

起初我觉得很简单。我的输入是金额,用户可以输入。然后,我根据用户的金额输入制作了javascript代码来计算动态价格。代码如下:

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

javascript:

jQuery("input[name='Gift-Card 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"/>

我想要根据商店名称和金额来改变价格。所以我创建了这个对象:

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

因此,根据输入的商店名称,可以使用预设值替换该值而不是常量0.95。我不知道如何让这两个人一起工作。意思是,我如何重新编码第一个javascript来重新调整var存储值而不是0.95?

3 个答案:

答案 0 :(得分:0)

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

我还建议您将Stores从文字输入更改为<select>。这样,您就不会依赖用户正确拼写商店,包括大写。

<select name="name" class="storeName">
    <option value="">Please select a store</option>
    <option value=".90">McDonalds</option>
    <option value=".92">Target</option>
</select>

然后你可以使用

var calc = parseFloat(jQuery(this).parents("form").find(".storeName").val());

答案 1 :(得分:0)

我会这样做:

function calcPrice(element) {
  // Use the element that called the listener to find the form
  var form = element.form;
  // Access form controls as named properties of the form
  var amt = form["Gift-Card Amount"].value;

  // Don't clear the value if it's not suitable, it's annoying
  // Let the user fix it themselves
  if (parseFloat(amt) != amt) {
    alert("Gift card amount is not a suitable value")
  }

  // Set the price
  form.price.value = amt * form.store.value;
}

</script>

示例表单,包含所有商店值。这样,您可以获得服务器获取所有相关值的后备,您不依赖于客户端计算。

<form>
  Store:
  <select name="store" onchange="calcPrice(this)">
   <option value="0.90">McDonalds
   <option value="0.92">Target
  </select>
  <br>
  Gift card amount:
  <input name="Gift-Card Amount" onchange="calcPrice(this)">
  Price:
  <input name="price" readonly>
</form>

答案 2 :(得分:0)

写一个可能返回正确值的小函数

function retrieveStoreValue(store){
      return stores[store];
} // be sure stores is defined before the first call of this one

并在你的更改函数中调用它

var storeName = jQuery(this).parents("form").find("input[name='name']").val();

var calc = parseFloat(this.value) * (retrieveStoreValue(storeName) );