【问题标题】:Enable/Disable textbox and button using JavaScript使用 JavaScript 启用/禁用文本框和按钮
【发布时间】:2025-12-18 07:25:02
【问题描述】:

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

【问题讨论】:

  • 我认为您正在寻找 $('#textbox').prop('disabled', true);

标签: javascript disabled-input


【解决方案1】:

你可以使用JQuery:

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

并再次启用它:

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

或者使用纯 JavaScript:

禁用:

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

启用:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 这真的帮助我尝试了不同的变量和设置,谢谢!!