ข้อมูลถูกเก็บไว้เป็น string ยาวๆ โดยแบ่งหัวข้อย่อยโดยใช้ @ นำหน้า ต้องการให้แสดงใน textarea โดยขึ้นบรรทัดใหม่ที่ละหัวข้อจะได้อ่านง่ายหน่อย
การเขียนให้ javascript จัดรูปแบบให้เขียนได้ในบรรทัดเดียว
1 | string.split( '\n' ).join( '' ).split( '@' ).join( '\n@' ).replace(/^\s/, '' ); |
ทดลอง หรือเขียนดูเอง ถ้า textarea id เท่ากับ detail จะเขียน code ง่ายๆได้เป็น
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <!doctype html> <html> <head> <meta charset= "utf-8" > <title>jQuery: textarea newline</title> <link href= "../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel= "stylesheet" type= "text/css" > </head> <body> <h1>Textarea newline</h1> <form action= "values.php" class = "form-horizontal" id= "formA" method= "post" > <div class = "form-group" > <label for = "detail" >Example textarea</label> <textarea class = "form-control" id= "detail" rows= "10" ></textarea> </div> </form> <div class = "col-sm-12" id= "resultA" ></div> <script src= "../vendor/components/jquery/jquery.min.js" ></script> <script> $(document).ready( function () { let textarea = $( '#detail' ); function format() { let temp = textarea.val().split( '\n' ).join( '' ).split( '@' ).join( '\n@' ).replace(/^\s/, '' ); textarea.val(temp); } format(); textarea.on( 'change' , function () { format(); }); }); </script> </body> </html> |
About the author