简体   繁体   中英

How to take absolute value in math function in javascript

I am trying to minus the value of "f1" from "f2" it works fine. However i want it just once but when i click the submit more more button it reduces every time the value of f1 from f2. How can it be done only once. It works well when i put value instead of when i call it from script.

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

pls help

JavaScript中数学函数中的绝对值是Math.abs();。

Math.abs(6-10) = 4;

不确定确切要执行的操作,但要使用Math.abs()计算绝对值。

If you want the function to only work once, you can have something like this:

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

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

Your question seems to be asking how to only subtract f1 from f2 only once, no matter how many times the submit button is clicked. One way to do it would be to have a variable that tracks if the function has been called already, and don't do the calculation if it has. As for the title mentioning absolute value, this is called by 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;
}

In order to get the function to be able to work again when the value of f1 changes, simply change the variable alreadyDone back to false when f1 changes

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM