-2

The problem is: I have an input text type element, and a button beside it.

Once the button is clicked, the selected text inside the input must wrap with a html element. For example, when the button is clicked, the selected text wrapped with <span style='color:red'></span> !

Does anyone has any solution ?

nicael
  • 18,550
  • 13
  • 57
  • 90

2 Answers2

2

As @RémyJ wrote, you can use jQuery select event, to get the selection. Try this:

var start, end;
$('#tf').select(function(e) {
    start = e.target.selectionStart;
    end = e.target.selectionEnd;
});

$('.wrap').click(function() {
    var val = $('#tf').val();
    var newVal = val.substr(0, start) + '!' + val.substr(start, (end-start)) + '!' + val.substr(end);
    $('#tf').val(newVal);
});

HTML:

<input type="text" id="tf"> 
<button type="button" class="wrap">wrap</button>

http://jsfiddle.net/qh95xyeq/

Mario A
  • 3,286
  • 1
  • 17
  • 22
0

A similar question has been asked here. You could use the JQuery select method (here) or the JS selection method (here). And then replace selection with HTML wrapped block.

Community
  • 1
  • 1
Rémy J
  • 108
  • 5