Updates from August, 2009 Hide threads | Keyboard Shortcuts

  • Generating Unique Strings in Javascript 

    jmaglasang 11:43 am on August 12, 2009 Permalink | Reply

    Here is a simple way to generate a unique string in javascript.

        var ts = (new Date()).getTime().toString();
        var url = "ajaxHandler.php?param1=value1&paramn=valuen&t=" + ts;
        //do ajax call...
    

    This method is very helpful for ajax developers, to overcome the problem of cached ajax requests in IE.

     
  • TextArea SelectedText, SelectionStart, SelectionEnd, SelStart, SelEnd (IE and FireFox) 

    jmaglasang 1:57 pm on April 30, 2009 Permalink | Reply

    Simple way of getting the html textarea’s selection properties selectedText, selectionStart, selectionEnd:

    Javascript:

     function getTextAreaSelection() {
       var textArea = document.getElementById('textarea1');
       if (document.selection) { //IE
           var bm = document.selection.createRange().getBookmark();
           var sel = textArea.createTextRange();
           sel.moveToBookmark(bm);
    
           var sleft = textArea.createTextRange();
           sleft.collapse(true);
           sleft.setEndPoint("EndToStart", sel);
           textArea.selectionStart = sleft.text.length
           textArea.selectionEnd = sleft.text.length + sel.text.length;
           textArea.selectedText = sel.text;
       }
       else if (textArea.selectionStart){ //FF
          textArea.selectedText = textArea.substring(textArea.selectionStart,textArea.selectionEnd);
       }
    
       alert("Selection Start==> " + textArea.selectionStart + "\n" +
          "Selection End  ==> " + textArea.selectionEnd + "\n" +
          "Selected Text  ==> " + textArea.selectedText + "\n" +
          "TextArea Value ==> " + textArea.value);
     }
    

    HTML:

    <textarea id="textarea1"></textarea> <button onclick="getTextAreaSelection()">Get Selection Info</button>
    
     
    • Jim 7:50 am on September 6, 2009 Permalink | Reply

      What if the selected text is repeated within the content?

      “textArea.value.indexOf” will return the first instance of the selected text, but that may not be the text that is actually selected, they are just the same because they are repeated.

      For example: “My name is Fred, and his name is John.”

      If I select the second instance of “name is”, when I run your function I will get the first. This isn’t a problem if you just want to know the text that is selected, but it is if you want to manipulate it.

    • jmaglasang 1:59 pm on September 10, 2009 Permalink | Reply

      You have a point there them, I have update the code but there is still a little problem, it cannot return the correct caret position in IE.

c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
esc
cancel