[英]Javascript how to copy multiple text boxes into one text box
I have three separate text boxes and want a button which copies all the content from the boxes into a 4th box. 我有三个单独的文本框,并希望有一个按钮将所有内容从框中复制到第4个框中。 How can I do this with javascript? 如何使用javascript执行此操作?
<form>
<textarea cols="60" rows="5" id="box1">PAST: </textarea>
<br /><br />
<textarea cols="60" rows="5" id="box2">PRESENT: </textarea>
<br /><br />
<textarea cols="60" rows="5" id="box3">FUTURE: </textarea>
<br /><br />
<input name="" type="button" />
<br /><br />
<textarea cols="60" rows="5" id="box4">All Past Present Future</textarea>
</form>
You just extract textarea values - and make their concatenation a value of this 'aggregate' textarea. 您只需提取textarea值-并将它们的串联作为此“汇总” textarea的值即可。 It's quite easy to do with jQuery, like this: 使用jQuery非常容易,如下所示:
$('#button_id').click(function() {
$('#box4').val(
$('#box1').val() + $('#box2').val() + $('#box3').val()
);
});
jsFiddle: http://jsfiddle.net/wCPbY/3/ jsFiddle: http : //jsfiddle.net/wCPbY/3/
// Runs on document ready
$(document).ready(function()
{
// Grabs each text in the textareas based on the id, added spaces in between.
var text = $("#box1").text() + " " + $("#box2").text() + " " + $("#box3").text();
// Appends the text to box4.
$("#box4").text( text );
});
With jQuery you can create a selector that will capture all the required elements. 使用jQuery,您可以创建一个选择器,该选择器将捕获所有必需的元素。 You might want to alter your HTML to give the elements matching class attributes so the selector will be able to group them together. 您可能想要更改HTML,以提供与类属性匹配的元素,以便选择器能够将它们分组在一起。
<textarea cols="60" rows="5" class="textGroup" id="box1">PAST: </textarea>
<textarea cols="60" rows="5" class="textGroup" id="box2">PRESENT: </textarea>
<textarea cols="60" rows="5" class="textGroup" id="box3">FUTURE: </textarea>
<textarea cols="60" rows="5" id="box4">All Past Present Future</textarea>
The selector to get all of the textareas would be - $(".textGroup")
. 获取所有文本区域的选择器将是- $(".textGroup")
。
Now all we have to do is iterate over all of them, collecting their contents and appending it to the main All Past Present Future
textarea. 现在,我们要做的就是遍历所有这些对象,收集它们的内容并将其附加到主要的All Past Present Future
文本区域中。
var wholeString = '';
$(".textGroup").each(function(index,elem){
wholeString += $(elem).text();
});
$("#box4").text(wholeSrting);
You don't need to load in an entire JavaScript library like jQuery. 您无需像jQuery一样加载整个JavaScript库。 Try this simple JavaScript (built for scalability!) 试试这个简单的JavaScript(为可伸缩性而构建!)
var textboxes = document.getElementsByTagName('textarea'),
box4 = document.getElementById('box4'),
i;
for (i = 0; i < textboxes.length - 1; i++) {
box4.value += textboxes[i].value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.