Iurie
Iurie

Reputation: 2248

Combine multiple textarea inputs into one textarea and make it editable with jQuery

I have a jQuery code that combine multiple user textarea inputs into one textarea, but the last is not editable. How to acquire this (without buttons or any supplementary clicks)?

$(document).on("change keyup", function () {
    var form = $('.combine').not('#Voltes5');
    var vals = form.map(function () {
        var value = $.trim(this.value)
        return value ? value : undefined;
    }).get();
    $('#Voltes5').val(vals.join(', '))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="combine" id="input1"></textarea>
<textarea class="combine" id="input2"></textarea>
<textarea class="combine" id="Voltes5"></textarea>

Upvotes: 0

Views: 118

Answers (1)

Pranav Rustagi
Pranav Rustagi

Reputation: 2731

The reason why it was happening was because the event was bind with document. So, whenever events like change or keyup were taking place, the text inside first two textareas was getting added to the third one (even if these events were taking place for third textarea).

To resolve it, I have added this code. The event is bind with document. However, changes will take place only when those event will happen for first two textareas. My selector is a lil different, but will help in case you have many textareas. :)

NOTE : This code will let you type inside the third textarea, but in case you type inside first two textareas, the text you typed inside third one will get lost.

var selector = '.combine[id^=input]';

$(document).on("change keyup", selector, function() {
  var vals = $(selector).map(function() {
    var value = $.trim(this.value)
    return value ? value : undefined;
  }).get();
  $('#Voltes5').val(vals.join(', '))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="combine" id="input1"></textarea>
<textarea class="combine" id="input2"></textarea>
<textarea class="combine" id="Voltes5"></textarea>

Upvotes: 1

Related Questions