Javascript 当用户单击按钮时,将一串文本添加到输入字段中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13941055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a string of text into an input field when user clicks a button
提问by Z with a Z
Basically just trying to add text to an input field that already contains a value.. the trigger being a button..
基本上只是尝试将文本添加到已经包含值的输入字段..触发器是一个按钮..
Before we click button, form field would look like.. (user inputted some data)
在我们点击按钮之前,表单域看起来像..(用户输入了一些数据)
[This is some text]
(Button)
After clicking button, field would look like.. (we add after clickingto the current value)
单击按钮后,字段看起来像..(我们添加after clicking到当前值)
[This is some text after clicking]
(Button)
Trying to accomplish using javascript only..
试图仅使用 javascript 来完成..
回答by PhearOfRayne
Example for you to work from
您的工作示例
HTML:
HTML:
<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?
jQuery:
jQuery:
<script type="text/javascript">
$(function () {
$('#button').on('click', function () {
var text = $('#text');
text.val(text.val() + ' after clicking');
});
});
<script>
Javascript
Javascript
<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
var text = document.getElementById('text');
text.value += ' after clicking';
});
</script>
Working jQuery example: http://jsfiddle.net/geMtZ/?
工作 jQuery 示例:http: //jsfiddle.net/geMtZ/?
回答by Hat
this will do it with just javascript - you can also put the function in a .js file and call it with onclick
这将仅使用 javascript 即可完成 - 您也可以将该函数放在 .js 文件中并使用 onclick 调用它
//button
<div onclick="
document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>
回答by Peter Rasmussen
Here it is: http://jsfiddle.net/tQyvp/
这是:http: //jsfiddle.net/tQyvp/
Here's the code if you don't like going to jsfiddle:
如果你不喜欢去 jsfiddle,这是代码:
html
html
<input id="myinputfield" value="This is some text" type="button">?
Javascript:
Javascript:
$('body').on('click', '#myinputfield', function(){
var textField = $('#myinputfield');
textField.val(textField.val()+' after clicking')
});?

