javascript设置input readonly或disabled属性子

发布时间:2020-07-21编辑:脚本学堂
javascript设置input readonly与disabled只读属性的几个例子,disabled 属性的作用是禁用,readonly 属性为只读,但没有禁用,通过具体例子来了解下吧。

javascript设置input标签readonlydisabled属性,借助按钮控制一个文本框值是否可以修改。

在js中控制标签属性的方法。

例1,
 

复制代码 代码示例:
<input type="text" id="Cs" value="123"  />
<script type="text/javascript">
 var Js_Cs= document.getElementById("Cs");
 Js_Cs.readOnly=true;
</script>

注意,此时JavaScript代码要写到<input>标签后面。

说明:
disabled 属性的作用是禁用
readonly 属性为只读,但没有禁用
通过表单提交,拥有disabled属性的表单元素处理页面是获取不到其值的,而readonly则可以。

例2,
 

复制代码 代码示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>readonly与disabled属性_www.jb200.com</title>
</head><body>
<input type="text" name="mytext" id="mytext" />
<script type="text/javascript">
//readOnly
document.getElementById("mytext").readOnly = true;
//disabled
document.getElementById("mytext").disabled = true;
</script>
</body>
</html>

例3,readonly只读属性设置
 

复制代码 代码示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>readonly只读属性_www.jb200.com</title>
</head><body>
<form action="#" method="post">
<input type="text" id="txt"/>
<input type="button" id="btn" value="切换成readonly状态" onclick="test()" />
</form>
<script type="text/javascript">
function test(){
 var txt=document.getElementById("txt");
 var btn=document.getElementById("btn");
 if(txt.readOnly)
 {
  txt.readOnly=false;
  btn.value="切换成readonly状态";
 }
 else
 {
  txt.readOnly=true;
  btn.value="切换成可以输入状态";
 }
}
</script>
</body>
</html>

例4,disabled:
 

复制代码 代码示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>disabled属性设置_www.jb200.com</title>
</head><body>
<form action="#" method="post">
<input type="text" id="txt"/>
<input type="button" id="btn" value="切换成disabled状态" onclick="test()" />
</form>
<script type="text/javascript">
function test(){
 var txt=document.getElementById("txt");
 var btn=document.getElementById("btn");
 if(txt.disabled)
 {
  txt.disabled=false;
  btn.value="切换成disabled状态";
 }
 else
 {
  txt.disabled=true;
  btn.value="切换成可以输入状态";
 }
}
</script>
</body>
</html>