Home > Back-end >  Get div's value to insert to textarea js
Get div's value to insert to textarea js

Time:09-25

I have a div behaving as a textarea where I can insert text. I want to mirror value as user typing in this div, to a second textarea in order to be formatted and to send to DB consequently. However, I seem to be having trouble taking div's value. It worked smoothly as I had a regular textarea. Here I used .text() instead of .val() but it doesn't add br. It is supposed to add br as user start a new line.

https://jsfiddle.net/u7mh431k/

$('#fake_textarea').keyup(function(){

  var val = $('#fake_textarea').text();

  val = val.replace(/\n/g, '<br />\n')

  $('#second').val(val);
});
   
.textbox {
-moz-appearance: textfield-multiline;
      -webkit-appearance: textarea;
      border: 1px solid gray;
      font: medium -moz-fixed;
      font: -webkit-small-control;
      height: 28px;
      overflow: auto;
      padding: 2px;
      resize: both;
      width: 200px;
      min-height: 50px;
}

textarea {
  width: 200px;
  height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="textbox" id="fake_textarea" contenteditable></div>
<textarea type="text" id="second"></textarea>

CodePudding user response:

Easy using vanilla JS.

The text you enter in your divis internally wrapped into sub-div elements. Just connect those subdivs' textContentwith a newline character, and assign it to the textarea's textContent.

fake_textarea.addEventListener('input', (e) => {
  second.textContent = [...fake_textarea.querySelectorAll('div:not(.textbox)')].map(e => e.textContent).join('\n')
})
.textbox {
  -moz-appearance: textfield-multiline;
  -webkit-appearance: textarea;
  border: 1px solid gray;
  font: medium -moz-fixed;
  font: -webkit-small-control;
  height: 28px;
  overflow: auto;
  padding: 2px;
  resize: both;
  width: 200px;
  min-height: 50px;
}

textarea {
  width: 200px;
  height: 50px;
}
<div class="textbox" id="fake_textarea" contenteditable></div>
<textarea type="text" id="second"></textarea>

CodePudding user response:

When using contenteditable, the child element is created in html element, so you have to parse it and change it to text. The appropriate property at this time is textContent.

$('#fake_textarea').keyup(function(){
  var val = $('#fake_textarea')
    .contents()
    .map((_,el)=> el.textContent   '<br/>\n')
    .toArray()
    .join('');
 
  $('#second').val(val);
});
  • Related