简体   繁体   中英

Note taking feature, line break and no content

I'm building the feature to take notes on my web app. I'm running into two problems:

I can't figure out how to recognize line breaks. I can hardcore text with line breaks, but when user clicks Edit it shows on the text the <br> and if he saves it just shows <br> in plain text.

Also if the user deletes all the text and clicks save it doesn't work and just prints <textarea> .

Any help is greatly appreciated!

 $('#edit').click(function() { $('#edit').hide(); $('#note').each(function() { var content = $(this).html(); $(this).html('<textarea style="width:inherit">' + content + '</textarea>'); }); $('#save').show(); }); $('#save').click(function() { $('#save').hide(); $('textarea').each(function() { var content = $(this).val(); //.replace(/\\n/g,"<br>"); $(this).html(content); $(this).contents().unwrap(); }); $('#edit').show(); }); 
 #note { word-wrap: break-word; max-width: 40rem; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-md-6"> <h5 class="card-tittle">Note</h5> <hr> <div class="container index"> <div class="row"> <div class="jumbotron col-md-12" id="note"> Test Text. </div> <div class="col-md-12"> <button class="btn btn-primary" id="edit"><span class="glyphicon glyphicon-edit"></span>Edit</button> <button class="btn btn-primary" id="save"><span class="glyphicon glyphicon-save"></span>Save</button> </div> </div> </div> </div> 

I think you want to do something like this...

$('#edit').click(function() {
  $('#edit').hide();
  $('#note').each(function() {
    var content = $(this).html().replace(/<br>/g,"\n");
    $(this).html('<textarea style="width:inherit">' + content + '</textarea>');
  });
  $('#save').show();
});

$('#save').click(function() {
  $('#save').hide();
  $('textarea').each(function() {
    var content = $(this).val().replace(/\n/g,"<br>"); //.replace(/\n/g,"<br>");
    $(this).html("");
    $(this).append(content);
    $(this).contents().unwrap();
  });
  $('#edit').show();
});

Demo: https://www.codeply.com/go/hAL9pWWUFk

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