首页 > 解决方案 > 从字段中动态读取值

问题描述

我有以下代码:

<!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>

我不想在单击按钮时运行该函数,而是运行它并动态显示第一个字段中的值,并在网站内容中显示值而不是弹出窗口。

我怎样才能做到这一点?提前感谢您的提示和帮助!

标签: javascriptjquery

解决方案


添加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>


推荐阅读