Search code examples
javascriptdisabled-input

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

Solution

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