0

Here we go again. I've been looking all day for a solution for this problem...

I got the code:

var formatString = function(t,style){
    var el = $(t);
    var pre;
    var start;
    var end;
    var len;
    var replace;
    switch(style){
        case 'italic':
            pre = '[em]';
            break;
        case 'bold':
            pre = '[b]';
            break;
        case 'paragraph':
            pre = '[p]';
            break;
    }

    if(document.selection){
        el.focus();
        var sel = document.selection.createRange();
        // Finally replace the value of the selected text with this new replacement one
        sel.text = pre + sel.text + pre.replace(/(\[)/,'[/');
    } else {
        len = el.val().length;
        start = t.selectionStart;
        end = t.selectionEnd;
        sel = el.val().substring(start, end);
        replace = pre + sel + pre.replace(/(\[)/,'[/');
        el.val(el.val().substring(0,start) + replace + el.val().substring(end,len));
    }

}

What I'm doing is creating a simple wysiwyg just to add some formating to the text that obviously is processed to show the correct html tags. All is working great of course with any browser but IE.

The problem that's happening that the beloved IE deselect any text selected when you click outside the textarea. And this is causing that the object sel.text has not text on it.

I run the function like this:

<button onclick="formatString($('#textid')[0],'italic')">Italic</button>

When you click the button other browsers output

'the italic text' // output the [em]italic[/em] text - when italic is selected
IE output 'the [em][/em]italic text'

If this is the same as another thread just guide me to it, literally I have read over 200 threads and nothing pointed out this problem.

raphie
  • 3,285
  • 2
  • 29
  • 26

1 Answers1

0

OK, because nobody has an answer I extended my research and read around 100 threads more, it's a joke.

I found the answer in the following threads:

Why getting a text selection from textarea works when a button clicked but not when a "div" clicked (Internet Explorer)

How to prevent buttons to submit a form.

Both here in stackoverflow.com,

For any reason IE lose the focus out of the textarea when an element other than a button is clicked, in my case a span made to look like a button with css. But the problem is that clicking a button submit a form and I didn't want that to happened, that's why I choose to masked a span.

Because IE behavior I used the button tag instead and in the onclick attribute add:

<button onclick="formatString($('#textid')[0].'italic'); return false">Italic</button>

The only problem with this solution is as follow, if a function throws an exception submit the form any way. So I have to change the code a little bit to avoid exceptions. A bad code habit of mine. Making the code hard to debug.

More info on this in the last thread linked.

Community
  • 1
  • 1
raphie
  • 3,285
  • 2
  • 29
  • 26