• ホーム
  • JavaScript
  • テキストエリアのカーソル位置にボタンクリックで指定文字を挿入

テキストエリアのカーソル位置にボタンクリックで指定文字を挿入

テキストエリアのカーソル位置にボタンクリックで指定文字を挿入

テキストエリアの任意の場所(カーソル位置)にボタンクリックで指定文字を挿入するコード。

テキストエリアにカーソルが無い場合、行頭に挿入され、挿入button(指定文字)は、幾つでも追加できます。

freoのオプションを任意の場所に挿入したい場合に便利かも。

<script>
(function(){
 document.addEventListener('click', function(evt){
  var t = evt.target;
  if (t.tagName == 'BUTTON' && /(^| )ContributionForm( |$)/.test(t.form.className)){
   var content = t.form.elements['content'];
   var pos = content.selectionStart;
   var moji = content.value.substring(0, pos);
   //var moji2 = content.value.substring(pos, content.value.length);
   content.value = moji + t.value;
  }
 }, false);
})();
</script>
<form action="#" class="ContributionForm">
<textarea name="content" cols="50" rows="10"></textarea>
<hr>
<button type="button" value="[file1]">[file1]</button>
<button type="button" value="[file2]">[file2]</button>
<button type="button" value="[file3]">[file3]</button>
<button type="button" value="[file4]">[file4]</button>
<button type="button" value="[file5]">[file5]</button>
</form>
JavaScript
2019.07.06 07:07
2019.07.12 07:06

Related entry

Pickup entry