繁体   English   中英

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

[英]Enable/Disable textbox and button using JavaScript

我正在学习 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;
}

您可以使用 JQuery:

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

并再次启用它:

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

或者使用纯 JavaScript:

禁用:

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

使能够:

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

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

您可以查看一些库,如jQuery (玩 DOM 操作)和/或lodash (帮助进行集合操作)来帮助您。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM