Miss Juhasz
Miss Juhasz

Reputation: 3

Enable/Disable textbox and button using JavaScript

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

Upvotes: 0

Views: 5608

Answers (2)

TResponse
TResponse

Reputation: 4125

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

Upvotes: 3

Arnaud JOLLY
Arnaud JOLLY

Reputation: 221

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/

Upvotes: 0

Related Questions