0

I'm learning JavaScript and need to disable a text box (annual interest rate) after it finished the for loop and displays the future value. I also need to modify the clear_click event so the textbox is enabled when the clear button is clicked, here is my code:

var $ = function (id) {
return document.getElementById(id);
}

var calculate_click = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );

$("futureValue").value = "";

if (isNaN(investment) || investment <= 0) {
    alert("Investment must be a valid number\nand greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0) {
    alert("Annual rate must be a valid number\nand greater than zero.");
} else if(isNaN(annualRate) || annualRate >= 20) {
    alert("Annual rate must be a valid number\nand less than twenty.");
} else if(isNaN(years) || years <= 0) {
    alert("Years must be a valid number\nand greater than zero.");
} else if(isNaN(years) || years >= 50) {
    alert("Years must be a valid number\nand less than fifty.");    
} else {
    var monthlyRate = annualRate / 12 / 100;
    var months = years * 12;
    var futureValue = 0;

    for ( i = 1; i <= months; i++ ) {
        futureValue = ( futureValue + investment ) *
            (1 + monthlyRate);
    }
    $("futureValue").value = futureValue.toFixed(2);
} 
}

var clear_click = function () {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("futureValue").value ="";
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
$("clear").onclick = clear_click;
}
1
  • 1
    i think you are looking for $('#textbox').prop('disabled', true); Commented Jan 22, 2015 at 20:18

2 Answers 2

3

You can use JQuery:

$('#textbox').attr('disabled', 'disabled');

and to enable it again:

$('#textbox').removeAttr("disabled");

Or use pure JavaScript:

Disable:

document.getElementById("textboxId").setAttribute("disabled", "disabled");

Enable:

document.getElementById("textboxId").removeAttribute("disabled"); 
Sign up to request clarification or add additional context in comments.

Comments

0

It seems that you're not using any library yet so let's play with basic Javascript.

You can have a look at some libraries like jQuery (to play with DOM manipulation) and/or lodash (help with collection manipulations) to help you.

To play with the disabled property of DOM input element in pure javascript, look at this jsfiddle: http://jsfiddle.net/arnaudj/nrnyo4e9/

1 Comment

This really helped me play around with the different variables and settings, thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.