Copying text of textarea into div with line breaks

为君一笑 提交于 2019-11-29 13:32:09

问题


I am tying to make a simple effect using keyup() in jQuery. I just want that when user types into the textarea then the text which user types will copy to another div named .content. When I press enter in textarea a new line is created but in my div the text is showing in the same line. My code is below or you can see demo here: http://jsfiddle.net/Pqygp/

    $('.content:not(.focus)').keyup(function(){					
        var value = $(this).val();
        var contentAttr = $(this).attr('name');
        
        $('.'+contentAttr+'').html(value);
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="mas" rows="15" class="content"></textarea>
    <p>&nbsp;</p>
    <div class="mas" >Texts Comes here</div>

回答1:


You need to convert the literal newlines into <br> tags for proper output in the DIV.

$('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>'));

Shown in your code below:

    $('.content:not(.focus)').keyup(function(){					
                                    
                                    
        var value = $(this).val();
        var contentAttr = $(this).attr('name');
        
        $('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>')); //convert newlines into <br> tags
        
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea name="mas" rows="15" class="content"></textarea> <p>&nbsp;</p> <div class="mas" >Texts Comes here</div>

JSFiddle




回答2:


Add a white-space: pre-wrap rule to the div's CSS.

.mas {
    white-space: pre-wrap;
}

Demo: http://jsfiddle.net/Pqygp/13/




回答3:


Use this line: Fiddle

$('.'+contentAttr+'').html(value.replace(/\n/g,"<br>"));

The problem was that newlines don't create linebreaks in html, but <br> will.




回答4:


Try like

var value = $(this).();
var contentAttr = $(this).attr('name');

$('.'+contentAttr+'').html(value.replace(/\r?\n/g,"<br>"));

This is the DEMO




回答5:


If you use React:

render() {
  const nbOfTextareaRows = this.state.textareaValue.split('\n').length;

  return (
    <textarea
      value={this.state.textareaValue}
      onChange={e => this.setState({ textareaValue: e.target.value })}
      rows={nbOfTextareaRows}
    />
  );
}


来源:https://stackoverflow.com/questions/18145682/copying-text-of-textarea-into-div-with-line-breaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!