Home  >  Article  >  Web Front-end  >  How to add read-only attribute to input in jquery

How to add read-only attribute to input in jquery

青灯夜游
青灯夜游Original
2021-11-16 15:59:265213browse

Jquery method to add read-only attributes to input: 1. Use the "$("input")" statement to obtain the input object; 2. Use attr() to add read-only attributes to the obtained input object, syntax "input object.attr("readonly","readonly");".

How to add read-only attribute to input in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

Read-only attribute of input--readonly

readonly attribute specifies that the input field is read-only.

Read-only fields cannot be modified. However, users can still tab to the field and select or copy its text.

The readonly attribute prevents users from modifying the value until certain conditions are met (such as a checkbox being selected). Then, you need to use JavaScript to eliminate the readonly value and switch the input field to an editable state.

How to add readonly attribute to input in jquery?

In jquery, you can use the attr() method to add the readonly attribute to the input element.

attr() method sets or returns the attribute value of the selected element.

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("input").attr("readonly","readonly");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>
	</head>

	<body>
		<input type="text" value="hello"/><br /><br />

		<button>给input添加只读属性</button>
	</body>
</html>

How to add read-only attribute to input in jquery

Recommended related tutorials: jQuery video tutorial

The above is the detailed content of How to add read-only attribute to input in jquery. 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