如何用jQuery使一个文本输入不可编辑
一个包含输入文本区的HTML文档,任务是在jQuery的帮助下使输入的文本不可编辑。有两种方法,下面讨论。
方法1:我们将把属性readonly设置为true为了设置只读属性,我们将使用一个prop()方法
- 示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to make a text input
non-editable using JQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"></p>
Type Here: <input id="input" />
<br><br>
<button onclick="GFG_Fun()">
Click Here
<p id="GFG_DOWN"></p>
<script>
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to "
+ "perform the operation.";
function GFG_Fun() {
$("#input").prop("readonly", true);
el_down.innerHTML =
"Input element is now read-only";
}
</script>
</body>
</html>
- 输出:
方法2:我们要将属性readonly设置为true在这个例子中,我们将使用attr()方法来设置该属性值。
- 示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to make a text input
non-editable using JQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"></p>
Type Here: <input id="input" />
<br><br>
<button onclick="GFG_Fun()">
Click Here
<p id="GFG_DOWN"></p>
<script>
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to "
+ "perform the operation.";
function GFG_Fun() {
$("#input").attr("readonly", true);
el_down.innerHTML =
"Input element is now read-only";
}
</script>
</body>
</html>
- 输出: