使用JavaScript启用/禁用文本框和按钮

时间:2015-01-22 20:15:14

标签: javascript disabled-input

我正在学习JavaScript并需要在完成for循环后禁用文本框(年利率)并显示未来值。我还需要修改clear_click事件,以便在单击清除按钮时启用文本框,这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

您可以使用JQuery:

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

并再次启用它:

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

或者使用纯JavaScript:

禁用:

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

启用:

document.getElementById("textboxId").removeAttribute("disabled"); 

答案 1 :(得分:0)

您似乎还没有使用任何库,所以让我们玩基本的Javascript。

您可以查看一些库,例如jQuery(使用DOM操作)和/或lodash(帮助收集操作)来帮助您。

要在纯javascript中使用DOM输入元素的disabled属性,请查看此jsfiddle:http://jsfiddle.net/arnaudj/nrnyo4e9/