我有一个简单的 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/