Deselect contents of a textbox with javascript

后端 未结 8 1386
醉话见心
醉话见心 2020-12-10 13:47

I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):

$(\"#txt1\").select();

Is t

8条回答
  •  失恋的感觉
    2020-12-10 14:20

    To "focus a particular textbox WITHOUT selecting it": I would use the part of the patched jquery plugin jquery-fieldselection

    using that you can call

    $('#my_text_input').setSelection({"start":0, "end":0}); // leaves the cursor at the left
    

    or use this reduced version that places the cursor at the end of the text (by default)

    (function() {
    var fieldSelection = {
        setSelection: function() {
            var e = (this.jquery) ? this[0] : this, len = this.val().length || ;
            var args = arguments[0] || {"start":len, "end":len};
            /* mozilla / dom 3.0 */
            if ('selectionStart' in e) {
                if (args.start != undefined) {
                    e.selectionStart = args.start;
                }
                if (args.end != undefined) {
                    e.selectionEnd = args.end;
                }
                e.focus();
            }
            /* exploder */
            else if (document.selection) {
                e.focus();
                var range = document.selection.createRange();
                if (args.start != undefined) {
                    range.moveStart('character', args.start);
                    range.collapse();
                }
                if (args.end != undefined) {
                    range.moveEnd('character', args.end);
                }
                range.select();
            }
            return this;
        }
    };
    jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
    })();
    

    used this way:

    $('#my_text_input').setSelection(); // leaves the cursor at the right
    

提交回复
热议问题