2014-06-27 101 views
-4

好吧,我有JavaScript來計算HTML表單的動態價格。代碼如下:通過一個隱藏的輸入傳遞一個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); 
}); 

這與該輸入:

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

的JavaScript採用該值,計算價格,我想它來填充這個:

<input type="hidden" name="price" value=""/> 

我相信我的javascript是正確的。我需要做什麼才能使價格發揮作用?

+0

你爲什麼要改變「原始代碼」。 – Steve

+0

'「input [name ='Amount']」.value'是錯誤的,它應該是'this.value',因爲它在原來的 – dmullings

+0

因爲我真的不知道我在做什麼。 – user3784221

回答

0

確保將這些項目包裹在<form>標記中。

<form> 
    <input class="irrelevant typeahead" type="text" placeholder="Amount" name="Amount"/> 
    <br /> 
    <input type="hidden" name="price" value=""/> 
</form> 


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); 
}); 

我這裏有一個工作演示:http://jsfiddle.net/P55ge/

在我所作出的價格輸入文本字段,而不是爲了易於觀察值被設置的隱藏字段的演示。

另請注意,該字段僅在輸入有效數字後纔會更新,然後單擊字段輸入。以下報價是從jQuery文檔.change()http://api.jquery.com/change/

現在,當第二個選項,從下拉列表中選擇該警報顯示 。如果您更改 字段中的文本,然後單擊,也會顯示。但如果該字段失去焦點而內容 發生變化,則該事件不會被觸發。

相關問題