Js怎么控制文本框只读(javascript如何设置文本输入框)

Js怎么控制文本框只读(javascript如何设置文本输入框)

首页维修大全综合更新时间:2025-03-28 15:21:35

Js怎么控制文本框只读

1

/7

新建一个html文件,命名为test.html,用于讲解用JS实现改变文本框的只读属性。

2

/7

在test.html文件中,使用input标签创建一个文本输入框,代码如下:

3

/7

在test.html文件中,使用readonly="readonly"设置input文本框只读,不可更改。

4

/7

在test.html文件中,创建一个button按钮,用于点击按钮时,实现改变文本框的只读属性。

5

/7

在test.html文件中,给button按钮绑定onclick点击事件,当按钮被点击时,执行gb函数。

6

/7

在js标签中,创建一个gb函数,在函数内,通过文本框id获得对象,设置readOnly属性为false,即关闭input文本框的只读属性。

7

/7

在浏览器打开test.html文件,点击按钮,清除文本框只读属性,更改文本框的文字。

用js代码控制input框只读可以防止用户对数据的更改,有些情况下很实用。

例子:

复制代码 代码示例:

<html>

<head>

<title>js控制input框只读_www.jquerycn.cn</title>

<meta name="Generator" content="EditPlus">

<meta name="Author" content="">

<meta name="Keywords" content="">

<meta name="Description" content="">

</head>

<script language="JavaScript">

function isreadonly(){

var obj = document.getElementById("username");

obj.setAttribute("readOnly",true);

obj.style.backgroundColor="#d2d2d2";

}

function readwrite(){

var obj = document.getElementById("username");

obj.setAttribute("readOnly",false);

obj.style.backgroundColor="#ffffff";

}

</script>

<body>

<form name="addform" id="addform" method="post" action="" >

<input type="text" id="username" name="username">

<input type="button" name="只读" value="read" onclick="isreadonly();">

<input type="button" name="可写" value="write" onclick="readwrite();">

</form>

</body>

</html>

<!--

点击“read”按钮,input框不能书写,且变灰;点击“write”按钮,input框恢复。

大家还看了
也许喜欢
更多栏目

© 2021 3dmxku.com,All Rights Reserved.