简体   繁体   中英

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. How can I do this with 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. It's quite easy to do with jQuery, like this:

$('#button_id').click(function() {
  $('#box4').val(
    $('#box1').val() + $('#box2').val() + $('#box3').val()
  );
});

try this:

$('button').click(function(){
    var text = "";
    $('textarea:not(:eq(3))').each(function(){
       text += this.value
    })
    $('textarea:eq(3)').val(text)    
})

demo

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. You might want to alter your HTML to give the elements matching class attributes so the selector will be able to group them together.

<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") .
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.

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. Try this simple JavaScript (built for scalability!)

var textboxes = document.getElementsByTagName('textarea'),
    box4 = document.getElementById('box4'),
    i;

for (i = 0; i < textboxes.length - 1; i++) {
    box4.value += textboxes[i].value;
}

And here is your jsFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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