如何在jQuery中获取文本框的值
这篇文章的目的是演示我们如何使用jQuery获得文本框的值。需要对HTML,CSS和jQuery有一个基本的了解。这可以通过使用jQuery的val()方法来实现。
val()方法:该方法用于设置或返回所选元素的属性值。
语法:获取文本框值的方法
$().val()
步骤:
- 在你的本地系统中创建一个文件index.html。
- 在你的HTML正文中创建一个输入文件(类型为文本)。
- 为了获得输入文本的值,你需要将val()方法附加到那个特定的选定的输入元素上。
例子:在这个例子中,我们将看到输入val()方法的使用。我们采取一个输入文件(类型为文本),并给它附加一个输入事件监听器。当用户在文本框中键入任何字母或单词时,它将立即在输入框的底部显示该文本。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script type="text/javascript">
(document).ready(function () {
('.textbox').on('input', function () {
// Set the inner text of the
// of the span tag
('span').text(('.textbox').val());
});
});
</script>
<style>
.container {
display: flex;
justify-content: center;
}
h1 {
color: green;
}
span {
margin-top: 10px;
}
</style>
</head>
<body>
<h1 class="container">
GeeksforGeeks
</h1>
<div class="container">
<input class="textbox"
type="text" placeholder="Text" />
</div>
<span class="container"></span>
</body>
</html>
输出: