0

I am working on learning to make forms using HTML and Javascript. When I go to submit my form, it processes it, and I can see the result, but the page quickly resets so that the form is back to its starting state. How can I make sure the page doesn't reset when the function is done?

Here is the HTML for the form and the function that processes it:

<form name="calculator" onsubmit="return calculate(this);">
            Enter the value of the house: $
            <input type="text" name="homeValue" id="homeValue" size="7" /><br>
            <select name="selMortgage" id="selMortgage">
                <option>Select a mortgage length</option>
                <option>15-year mortgage</option>
                <option>30-year mortgage</option>
            </select></br>
            <p class="form"><input type="checkbox" name="chkDiscount" value="discount"/>Good Credit Discount?</p>
            <input type="submit" value="Calculate" />
            <div id="result"></div>
</form>

function calculate(form) {
    var amountEntered = form.homeValue.value;
    var termLength;
    var interestRate;
    var calc;
    document.getElementById("result").innerHTML = "hi";
    if (!/^\d+(\.\d{1,2})?$/.test(amountEntered))
    {
        alert("You did not enter an amount of money");
        //form.homeValue.focus();
        return;
    }
    if (form.chkDiscount.checked == true)
    {
        interestRate = .05;
    }
    else
    {
        interestRate = .06;
    }
    if (form.selMortgage.selectedIndex == 0)
    {
        alert("Select a mortgage length");
    }
    else if (form.selMortgage.selectedIndex == 1)
    {
        termLength = 15;
    }
    else if (form.selMortgage.selectedIndex == 2)
    {
        termLength = 30;
    }
    calc = (Math.pow(1+interestRate,termLength) * amountEntered)/(termLength*12);
    document.getElementById("result").innerHTML = calc.toFixed(2);
}
4

4 に答える 4

3

It looks like you are missing a return false.

于 2012-12-14T04:54:09.063 に答える
1

Since you are submitting the form the values are lost due to page reload. You may try to POST your values then assign the post values on your form elements so that even after refresh youre still able to see the POST data submitted..

于 2012-12-14T04:46:49.307 に答える
1

Try this:

Just use return false; at the end of your javascript function.

于 2012-12-14T04:52:40.800 に答える
0

When the form is submitted, the JS function calculate will be invoked. Since the function does not return any value, undefined will be assumed. And in JS the undefined will be assumed to nothing and the form will be submitted to server and reload again. This is why you lose your data. From your code, the page just execute some JS code. So we can prevent submitting the form to keep your data. You may need to return false in calculate function to prevent submitting. Example as below:

document.getElementById("result").innerHTML = calc.toFixed(2); return false;

于 2012-12-14T04:50:36.997 に答える