Home  >  Article  >  Web Front-end  >  How to set input box to read-only in javascript

How to set input box to read-only in javascript

青灯夜游
青灯夜游Original
2021-12-08 17:38:018788browse

Setting method: 1. Use the "document.getElementById(id)" statement to obtain the input element object according to the specified id value; 2. Use the "input object.setAttribute("readOnly", true)" statement to obtain the input element Add read-only style.

How to set input box to read-only in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, if you want to set the input box to read-only, you only need to use the setAttribute() method to add the read-only attribute --readOnly to the input element.

The setAttribute() method adds the specified attribute and assigns it the specified value.

Grammar:

element.setAttribute(attributename,attributevalue)

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
	</head>
	<body>
		<input type="text" id="text" /><br><br>
		<input type="button" value="设为只读" id="btn" />
		<script>
			function my(id) {
				return document.getElementById(id);
			}
			my("btn").onclick = function() {
				my("text").setAttribute("readOnly", true);
			}
		</script>
	</body>
</html>

How to set input box to read-only in javascript

##[Related recommendations:

javascript learning tutorial

The above is the detailed content of How to set input box to read-only in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn