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

How to set input box to read-only in javascript

青灯夜游
Release: 2021-12-08 17:38:01
Original
8916 people have browsed it

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)
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template