2013-03-25 22 views
1

我想從「f2」減去「f1」的值,它工作正常。不過,我只需要它一次,但是當我點擊提交更多按鈕時,它會減少每次f2的f1值。它如何只能做一次。當我把價值,而不是從腳本調用時,它運作良好。如何在JavaScript中取數學函數的絕對值

<form name=bills> 

<p><input type="text" name="f1" size="20"> 
<input type="text" name="f2" size="20" value="30"></p> 
    <input type="button" value="Submit" onclick="cbs(this.form)" name="B1"> 

    <Script> 
    function cbs(form) 

    { 
     form.f2.value = (([document.bills.f2.value] * 1) - (document.bills.f1.value * 1)) 
    } 

請幫助

回答

1

在JavaScript中的數學函數的absulute值爲Math.abs();

Math.abs(6-10) = 4; 
1

不知道你想什麼做的,但計算絕對值使用Math.abs()

0

如果你希望函數只能使用一次,你可以有這樣的事情:

hasBeenRun = false; //have this variable outside the function 

if(!hasBeenRun) { 
    hasBeenRun = true; 
    //Run your code 
} 
0

你的問題好像是問如何只從F2減去F1只有一次,無論多少次提交按鈕被點擊。一種方法是創建一個跟蹤函數是否已被調用的變量,如果已經調用,則不執行計算。至於標題提的絕對值,這是由Math.abs(value)

<Script> 
var alreadyDone = false; 
function cbs(form) 
{ 
    if (alreadyDone) return; 
    // this one takes the absolute value of each value and subtracts them 
    form.f2.value = (Math.abs(document.bills.f2.value) - Math.abs(document.bills.f1.value)); 

    // this one takes the absolute value of the result of subtracting the two 
    form.f2.value = (Math.abs(document.bills.f2.value - document.bills.f1.value)); 
    alreadyDone = true; 
} 

爲了叫了功能,以便能夠重新工作時的F1的值發生變化,只是改變變量alreadyDone回假F1變化時

<input type="text" name="f1" onChange="alreadyDone=false;" size="20"> 
+0

Thx john。正如你所說的那樣工作。不過,我需要它不應該改變,但當F1的變化比它應該再次工作一次。 Thx再次約翰 – 2013-03-26 09:08:16

+0

@chandrabhushan,我編輯了我的答案,以顯示如何在F1更改時再次使功能工作。 – jonhopkins 2013-03-26 12:27:09

相關問題