例如,对于这样的输入:
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="form-group my-2">
<input class="form-control mx-2" type="text" placeholder="Customer Name">
</div>
<div class="form-group mb-2">
<input class="form-control mx-2" type="email" placeholder="Customer Email">
</div>
<div class="form-group mb-2">
<input class="form-control mx-2" type="text" placeholder="Customer pin">
</div>
<div class="form-group mb-2">
<textarea class="form-control mx-2" rows="4">
Hi, {customer Name here}
Your Email is: {customer Email here}
Your Pin is: {customer pin here}
</textarea>
</div>
</div>
</body>
则textarea值应变为
Hi, John Doe
Your Email is: johndoe@mail.com
Your Pin is: 123如何用用户输入的数据自动填充文本区域?
发布于 2022-08-02 03:57:18
您需要使用JavaScript。当输入值被更新时,它将从输入值构建完整的textarea内容。如下所示:
// Input elements
var customerName = document.getElementById("customer-name");
var customerEmail = document.getElementById("customer-email");
var customerPin = document.getElementById("customer-pin");
// Output textarea
var customerInfo = document.getElementById("customer-info");
function updateTextareaContent(){
customerInfo.value=`Hi, ${customerName.value||"(enter name)"}
Your Email is: ${customerEmail.value||"(enter email)"}
Your Pin is: ${customerPin.value||"(enter pin)"}`;
}
customerName.addEventListener("keydown", updateTextareaContent);
customerEmail.addEventListener("keydown", updateTextareaContent);
customerPin.addEventListener("keydown", updateTextareaContent);
customerName.addEventListener("keyup", updateTextareaContent);
customerEmail.addEventListener("keyup", updateTextareaContent);
customerPin.addEventListener("keyup", updateTextareaContent);<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="form-group my-2">
<input class="form-control mx-2" type="text" placeholder="Customer Name" id="customer-name">
</div>
<div class="form-group mb-2">
<input class="form-control mx-2" type="email" placeholder="Customer Email" id="customer-email">
</div>
<div class="form-group mb-2">
<input class="form-control mx-2" type="text" placeholder="Customer pin" id="customer-pin">
</div>
<div class="form-group mb-2">
<textarea class="form-control mx-2" rows="4" id="customer-info">
Hi, (enter name)
Your Email is: (enter email)
Your Pin is: (enter pin)
</textarea>
</div>
</div>
</body>
</html>
(代码片段有点大,因此被折叠,单击箭头打开它)
它监视文本中的更改,当这些更改发生时,它会更新文本区域。
为了更好地理解代码片段,下面是一些进一步的阅读:
https://stackoverflow.com/questions/73201760
复制相似问题