javascript - 使用表单按钮填充文本输入

标签 javascript html forms

我有一个简单的 html 表单,我在其中输入标题和描述,然后点击提交。页面顶部是一些我经常复制并粘贴到这些字段中的文本段落。这是一个重复性的任务,并且段落是用 php 动态生成的。

我可以在每个段落或 div 的末尾放置一个按钮或链接,以使用脚本填充我的表单输入字段吗?然后我所要做的就是点击提交。我已经在页面上使用了 jquery。

编辑:

<p>Sentence one.  Longer than this</p><!--would like a button here to populate field in form below-->
<p>Sentence two.  Longer than this</p>
<p>Sentence three.  Longer than this</p>

<form id="sampleform" action="actionpage.php" method="post">
Title<input type="text" name="title>
Desc<input type="text" name="title>
<input type="submit" value="Submit"></form>

最佳答案

如果您有一些选择器可以选择所有 <p>包含这些段落的标签,您可以执行如下操作:

$(function() {
  var $descInput = $('input[name=desc]');
  // wrap the text of each paragraph in a span so we can target it easily.
  // Then add a button inside each <p> at the end that will prepopulate that text.
  $('p.prefill').wrapInner('<span class="text"></span>').append('<button class="prefill-sentence">Prefill</button>');
  // Add a click handler for all the newly added buttons
  $('button.prefill-sentence').click(function() {
    // get the contents of the span we used to wrap the sentence with
    var sentence = $(this).prev('.text').text();
    // add that sentence to the current value of the description input
    $descInput.val($descInput.val() + sentence);
  });
});
.prefill-sentence {
  margin-left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="prefill">Sentence one. Longer than this</p>
<p class="prefill">Sentence two. Longer than this</p>
<p class="prefill">Sentence three. Longer than this</p>
<form id="sampleform" action="actionpage.php" method="post">
  Title
  <input type="text" name="title" />Desc
  <input type="text" name="desc" />
  <input type="submit" value="Submit" />
</form>

(注意,我假设您的描述输入的名称为“desc”。理想情况下,您可以使用类或 id 在实际代码中更轻松地定位它)。

关于javascript - 使用表单按钮填充文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258892/

相关文章:

javascript - 正则表达式匹配大括号内的内容,而嵌套大括号不会破坏它

javascript - 使用 jquery 更改后复选框未提交

html - 表格没有出现,但它的内容出现了

html - 以 html 形式设置验证消息的样式

javascript - 输入标签后换行

javascript - 将圆的半径(以米为单位)缩放到 D3.js d3.geo.mercator map

javascript - RegeneratorRuntime 未定义

javascript - 如何在 JavaScript 中处理对象定义与实例化?

IE中两行的html输入按钮

php - SQL数据库不存储用户输入