简体   繁体   English

如何将先前的输入值插入文本区域?

[英]How can I insert a previous input value into a textarea?

I'm new to HTML/CSS and have created a simple contact form to enter a name, number, and have a populated textarea with a short message but would like to automatically populate the name area within the text field with whatever was put into the name's input field previously in the contact form. 我是HTML / CSS的新手,并创建了一个简单的联系表单来输入姓名,电话号码,并使用短消息填充textarea ,但是我想自动将文本字段中的name区域填充到文本字段中。联系人表单中先前的姓名输入字段。 What is the best way to do this? 做这个的最好方式是什么?

<fieldset>
<h1>Contact Form</h1>
<label for="name">Patient Name:</label>
<input name="name" id="name" type="text" size="40" maxlength="100">
<label for="number">Patient Number:</label>
<input name="number" id="number" type="text" size="40" maxlength="12">
<label for="message">Text Messge:</label>
<textarea name="message" id="message" cols="40" rows="10">
Hi [name], thank you for visiting us!
</textarea>
<input class="btn" name="submit" type="submit" value="Send">
</fieldset>

Some JavaScript should solve your problem. 一些JavaScript应该可以解决您的问题。

Insert this script tag into your HTML file after the form. 将此script标记插入表单的HTML文件中。

<script>
  // save the location of the name field
  var name_field = document.getElementById('name');

  //add an event listener to activate if the value of the field changes
  name_field.addEventListener('change', function() {
    // when the field changes run the following code

    // copy the text (value)
    var name = name_field.value;

    // concatenate it with the desired message
    var autoFill = 'Hi ' + name + ', thank you for visiting us!';

    // and paste it into the message field.
    document.getElementById('message').value = autoFill;
  })
</script>

For dynamic behavior you are gonna need some javascript. 对于动态行为,您将需要一些javascript。

<input name="number" id="number" type="text" oninput="getNumber()" size="40" maxlength="12">

 <script>
var getNumber = function() {
    document.getElementById("message").innerHTML = "Hi " + document.getElementById("name").value + ", thank you for visiting us";
}
</script>

And as it looks right now, you probably shouldn't be using a textArea to display this message, rather use a paragraph element. 现在看来,您可能不应该使用textArea来显示此消息,而应该使用段落元素。 AngularJS is perfect for a scenario like this if you are more interested. 如果您对此感兴趣,AngularJS非常适合这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM