LoginSignup
2
2

More than 5 years have passed since last update.

[javascript]textarea内の文字をタグで囲む

Last updated at Posted at 2017-10-16

textarea内の文字をタグで囲む

仕様

  • 任意のtextareaに対して文字を選択して適当なタグで囲む

ソース

HTML

test_3.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="test_3.js"></script>
<title>test_3:textareaの文字をタグで囲む</title>
</head>
<body>
<textarea type="text" id="hoge" rows=10>
aaabbb
cccddd
eeefff
</textarea><br>
<input type="button" value="h1" class="tag">
<input type="button" value="h2" class="tag">
<input type="button" value="h3" class="tag">
</body>
</html>

javascript

test_3.js
$(function(){
  $('.tag').on('click',function(e){
    var v= $('#hoge').val();
    var selin = $('#hoge').prop('selectionStart');
    var selout = $('#hoge').prop('selectionEnd');
    var befStr="<"+$(this).val()+">";
    var aftStr="</"+$(this).val()+">";
    var v1=v.substr(0,selin);
    var v2=v.substr(selin,selout-selin);
    var v3=v.substr(selout);
    $('#hoge')
      .val(v1+befStr+v2+aftStr+v3)
      .prop({
        "selectionStart":selin+befStr.length,
        "selectionEnd":selin+befStr.length+v2.length
        })
      .trigger("focus");
  });
});
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2