Home >Web Front-end >Front-end Q&A >How to set text box read-only in jquery

How to set text box read-only in jquery

WBOY
WBOYOriginal
2022-04-08 15:46:463918browse

Method: 1. Use the "$(input element)" statement to obtain the text box element object; 2. Use the attr() method to set the text box read-only, and set the readonly attribute value to readonly. The syntax is: "Text box element object.attr("readonly","readonly")".

How to set text box read-only in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

How to set the text box read-only in jquery

1. Use the "$(input element)" statement to obtain the text box element object

$ is jQuery Another name for

And jQuery is a function provided by the jQuery library. (It seems that it is not just a function, because there is also the use of $.ajax(options), which is equivalent to jQuery.ajax(options))

The function of this function is to search and select elements in the html document based on the parameters in (). One of the functions of the function is to replace GetElementByID, but () can not only be ID, but also various selectors

For example:

$(document) is to select the entire document object

2, attr method

##attr() Method sets or returns the properties and values ​​of the selected element.

When this method is used to return an attribute value, the value of the first matching element is returned.

When this method is used to set attribute values, one or more attribute/value pairs are set for the matching element.

Syntax

Return the value of the attribute:

$(selector).attr(attribute)

Set the attribute and value:

$(selector).attr(attribute,value)

The 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 example is as follows:

<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(&#39;input&#39;).attr("readonly","readonly");
});
});
</script>
</head>
<body>
<input type="text" name="FirstName" value="Mickey">
<button>将文本框设置为只读</button>
</body>
</html>

Output result:

How to set text box read-only in jquery

Related video tutorial recommendation:

jQuery video tutorial

The above is the detailed content of How to set text box read-only 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