JQuery 设置一个输入文本字段的值
有一个输入元素,任务是使用JQuery来设置它的值。下面是讨论的几个例子。
要了解例子首先要知道几个方法。
JQuery val()方法:
该方法返回/设置所选元素的值属性。
如果我们使用这个方法来返回值,它将返回第一个被选中的元素的值。
如果我们使用这个方法来设置值,它将为一组选定的元素设置一个或多个值属性。
语法:
- 返回值属性。
$(selector).val()
- 设置值属性。
$(selector).val(value)
- 使用函数设置值属性。
$(selector).val(function(index, curValue))
参数:
- value。这个参数是必需的。它指定了value属性的值。
- function(index, currentValue)。这个参数是可选的。它指定了返回要设置的值的函数。
- index。它返回元素在集合中的索引位置。
- currentValue。它返回所选元素的当前值属性。
例子1:在这个例子中,输入元素的值是通过val()方法从其ID中选择输入元素来设置的。
<!DOCTYPE HTML>
<html>
<head>
<title>
JQuery | Set value of input text.
</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> Input Box:
<input id="input"
type="text"
class="Disable"
value="" />
<br>
<br>
<button id="setText">
setText
</button>
<script>
("#setText").click(function(event) {
('#input').val("GeeksForGeeks");
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子2:在这个例子中,输入元素的值是通过val()方法设置的,从其父元素中选择输入元素< body >
,然后选择< input >
。
<!DOCTYPE HTML>
<html>
<head>
<title>
JQuery
| Set value of input text.
</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> Input Box:
<input id="input"
type="text"
class="Disable"
value="" />
<br>
<br>
<button id="setText">
setText
</button>
<script>
("#setText").click(
function(event) {
('body input').val(
"GeeksForGeeks");
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。