javascript - 从字段中动态读取值
问题描述
我有以下代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("input:text").val());
});
});
</script>
</head>
<body>
Firstname: <input type="text" name="fname" value="Peter"><br>
Lastname: <input type="text" name="lname" value="Griffin"><br><br>
<button>Return the value of the first input field</button>
</body>
</html>
我不想在单击按钮时运行该函数,而是运行它并动态显示第一个字段中的值,并在网站内容中显示值而不是弹出窗口。
我怎样才能做到这一点?提前感谢您的提示和帮助!
解决方案
添加onkeyup
事件处理程序
function showInputVal(elem) {
$("#inputDisplay").text(elem.value)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Firstname: <input type="text" onkeyup="showInputVal(this)" name="fname" value="Peter">
<br> Lastname: <input type="text" onkeyup="showLastNameVal(this)" name="lname" value="Griffin">
<br><br>
<div id="inputDisplay"></div>
推荐阅读
- java - Settings.xml 没有从命令行获取我的 java8 配置文件
- java - 删除没有 JPA 映射的 1:1 父表单子实体
- c# - 处理同时连接两次数据库
- python - Python新手,我该如何循环?
- image-processing - 将 PCA 应用于 CNN 的图像时,我必须给它灰度图像吗?
- python - 如何在 scipy 差分进化中传递/访问目标函数内部使用的变量
- quarkus - Quarkus - 忽略 @Path("/") 的资源,而是从资源中加载内容
- amazon-web-services - 是什么导致带有 waithandle.url 的 cfn-signal 出现 403 错误
- c++ - 在 C++ 中具有明确定义的分配器的危险指针
- openssl - TLS 握手失败错误 w/OpenSSL 1.1.x