chandra bhushan
chandra bhushan

Reputation: 11

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

Upvotes: 1

Views: 4877

Answers (4)

jonhopkins
jonhopkins

Reputation: 3842

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">

Upvotes: 0

JP_
JP_

Reputation: 1666

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
}

Upvotes: 0

Derek Henderson
Derek Henderson

Reputation: 9706

Not sure exactly what you're trying to do, but to calculate absolute value use Math.abs().

Upvotes: 1

mysteriousboy
mysteriousboy

Reputation: 159

The absulute value in math function in JavaScript is Math.abs();

Math.abs(6-10) = 4;

Upvotes: 1

Related Questions