Html 使用javascript禁用文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18814166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:27:08  来源:igfitidea点击:

disable textbox using javascript

javascripthtml

提问by Asker

as the title says, i want to try to disable textbox when i open the file

正如标题所说,我想在打开文件时尝试禁用文本框

<form name='registration' action="registration.php" method="post" onSubmit="return    formValidation();">
            <table>
            <tr>
            <td>FirstName:</td>     
            <td><input type = "Text" name = "firstname" id="1"></p></td>
            </tr></table></form>

and with this javascript code i try to disable it

并使用此 javascript 代码我尝试禁用它

function formValidation(){
    var fn = document.registration.firstname;
    if(fname_validation(fn))  
    {}
document.getElementById("1").disabled=true;
}


function fname_validation(fn){
var fn_len = fn.value.length;
var fn_char = /^[A-Za-z]+$/;
if (fn_len == 0){
    alert("first name cannot empty");

    return false;
}
if(!fn.value.match(fn_char)){
    alert("first name must enter alphabet only");

    return false;
}
else{
return true;
}
}

why the text box still doesnt disable?

为什么文本框仍然没有禁用?

回答by service-paradis

First, there is no radio button. Second, when do you want to disable your text input? Right now, the function that make your input disabled is called on form submit. So, your input will be disabled only when you submit your form... probably too late. If you want to disable your input from start, your input should look like this

首先,没有单选按钮。其次,您想什么时候禁用文本输入?现在,在表单提交时调用禁用输入的函数。因此,只有在您提交表单时,您的输入才会被禁用……可能为时已晚。如果你想从一开始就禁用你的输入,你的输入应该是这样的

<input type = "Text" name = "firstname" id="1" disabled="disabled" />

Or if you want to disable it with javascript, you have to execute it on load. Something like this:

或者,如果您想使用 javascript 禁用它,则必须在加载时执行它。像这样的东西:

window.onload = function() {
   document.getElementById('1').disabled = true;
};

回答by tymeJV

If you want the textbox to be disabled on page load, add the disabledattribute to your input

如果您希望在页面加载时禁用文本框,请将该disabled属性添加到您的input

<input type = "Text" name = "firstname" id="1" disabled />