前提・実現したいこと
複数あるテキストフォーム(input type="text"、textarea)にフォーカスが当たっている状態で、テキストの一部又は全部を選択したときに、ボタンをクリックして対応するタグをテキストの前後に挿入したい。
試したこと
current = $(":focus");
でカーソルが当たっている要素を取得し、window.getSelection().toString()
で選択している範囲の値も取得できました。
ただここから、選択範囲の前後にタグを入れる方法がわかりません。
ボタンをクリックしたときに、current
に下のソースのようなことや、参考サイトのような.insertBeforeSelection('xxxx')
を試しました。がcurrent..insertBeforeSelection is not a function
とconsoleにエラーがでています。うまくいきません。
javascript
1 2$(function(){ 3 4 ..... 5 6 var current; 7 var inputVal; 8 9 $("#contents input").focusin(function(){ 10 current = $(":focus"); 11 console.log(window.getSelection().toString()); 12 } 13 14 $('#btn').on('click', function(){ 15 current.selection('insert', { 16 text: 'test', mode: 'before' 17 }).selection('insert', { 18 text: 'test', mode: 'after' 19 }); 20 }); 21 22 ..... 23 24});
HTML
1<button id="btn" type="button">button</button> 2<div id="contents"> 3 4 ... 5 // input type="text"とtextareaは複数あります。 6 // appendして追加することもあります。 7 8 <div> 9 <input type="text" value="xxxxxxxxxxxx"> 10 </div> 11 <div> 12 <textarea></textarea> 13 </div> 14 15 ... 16 17</div>
お詳しい方、ご教示願います。
追記
回答2件
あなたの回答
tips
プレビュー