Home > other >  Insert <br> tag to the second textbox JS
Insert <br> tag to the second textbox JS

Time:09-25

I'm building a simple text editor and I start with basics - as user press enter and start a new line a want to insert br to the the second textbox. The second textbox is meant to send ready formatted text to the database. As of now I managed to copy data from first to second textbox as user typing. Hence, I want to disable viewing br in the first textbox. Is there a way not to display br in the first textbox but technically have it. Thank you in advance!

DEMO: https://jsfiddle.net/mxr7hz3p/

Textboxes:

 <textarea type="text" id="first"></textarea>
 <textarea type="text" id="second"></textarea>

JS:

$(function (){
    $('#first').keyup(function (e){
        if(e.keyCode == 13){
            var curr = getCaret(this);
            var val = $(this).val();
            var end = val.length;
                
            $(this).val( val.substr(0, curr)   '<br>'   val.substr(curr, end));
    }})
});

    function getCaret(el) { 
       if (el.selectionStart) { 
          return el.selectionStart; 
       }
       else if (document.selection) { 
            el.focus(); 

            var r = document.selection.createRange(); 
                if (r == null) { 
                return 0; 
            } 

            var re = el.createTextRange(), 
            rc = re.duplicate(); 
            re.moveToBookmark(r.getBookmark()); 
            rc.setEndPoint('EndToStart', re); 

            return rc.text.length; 
         }  
         return 0; 
     }
$('#first').keyup(function(){
    $('#second').val(this.value);
});

CodePudding user response:

You can simplify the JS in the fiddle to do this

$('#first').keyup(function(){
  var val = $(this).val();

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

  $('#second').val(val);
});

https://jsfiddle.net/t3vzgnp7/2/

  • Related