简体   繁体   中英

Using jQuery selector and setSelectionRange is not a function

I have assembled a basic jfiddle below. For some reason my selector works to retrieve the textarea box to set the value, but the selector doesnt work to use the setSelectionRange function. On the console you'll find an error for .setSelectionRange is not a function.

http://jsfiddle.net/dMdHQ/6/

code(please refer to jfiddle): selector.setSelectionRange(carat,carat);

setSelectionRange(carat,carat) is not a method on jquery object. You want to use it on DOM element. So try:

selector[0].setSelectionRange(carat,carat); //use `[0]` or .get(0) on the jquery object

See Reference

Fiddle

HTML:

<input type="search" value="Potato Pancakes" id="search">

JQUERY:

jQuery.fn.putCursorAtEnd = function() {

  return this.each(function() {

    $(this).focus()

    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)

      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;

      this.setSelectionRange(len, len);

    } else {
    // ... otherwise replace the contents with itself
    // (Doesn't work in Google Chrome)

      $(this).val($(this).val());

    }

    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;

  });

};

$("#search").putCursorAtEnd();

Check:

http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

For me this is a good solution

selector[0].setSelectionRange(start ,end); 

But I would like to add one more thing. I noticed that setSelectionRange is something that becomes available asynchronously after the element gets focus.

var element = selector[0];
element.addEventListener('focus', function() {
   element.setSelectionRange(start, end); 
});
element.focus();

Also you can use alternatively:

element.selectionStart = start;
element.selectionEnd = end;

You could try this which works for me. I use it to build an address from the separate address fields and then do the copy for pasting.

The HTML

<div id="d_clip_container" style="position:relative">
    (<a href="#" id="d_clip_button">copy to clipboard</a>)
</div>;
<textarea id="clip" rows="0" cols="0" style="border:none;height:0;width:0;"></textarea>

The jQuery

    $(document).ready(function() {

        $('#d_clip_button').click(function() {
            //get all the values of needed elements
            var fName = $("#firstName").val();
            var lName = $("#lastName").val();
            var address = $("#Address").val();
            var city = $("#City").val();
            var state = $("#State").val();
            var zip = $("#Zip").val();
            //concatenate and set "clip" field with needed content
            $('#clip').val(fName + " " + lName + "\n" + address + "\n" + city + ", " + state + " " + zip);

            //Do it
            if(copyToClipboard('#clip')) {
                alert('text copied');
            } else {
                alert('copy failed');
            }
        });
    });

    function copyToClipboard(elem) {
        // set focus to hidden element and select the content
        $(elem).focus();
        // select all the text therein  
        $(elem).select();

        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch(e) {
            succeed = false;
        }

        // clear temporary content
        $(target).val('');

        return succeed;
    }       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM