Zhen
Zhen

Reputation: 12431

How to select (highlight) text in input textbox

Hi I am using haml and coffescript to write my code.

The code snippets are as follows

//haml code for input box and value
%input.detail_text{value: "<%= 'http://dailymus.es/#!/' + answer.user.nickname + '/muses/' + answer._id %>"}

Text input display (in a modal)

enter image description here

How can I modify my current coffescript code so that when I render my modal view, the text in the box will be highlighted as shown above.

I tried with the following code with no avail

//code to render the modal view
render: ->
    $(@el).html @template(@model.toJSON())
    //this is where I attempt to select the input box via jQuery and selecting the text
    $(@el).find('input.detail_text').focus().select()
    @

Thanks in advance

Upvotes: 2

Views: 3133

Answers (1)

jrumbinas
jrumbinas

Reputation: 426

Here is more advanced function to select range:

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if (this.nodeName === "INPUT"){
            var inputStart = Math.min(start || 0, this.value.length);
            var inputEnd = Math.min(
                               Math.max(end || this.value.length, inputStart),
                               this.value.length);
            if (this.setSelectionRange) {
                this.focus();
                this.setSelectionRange(inputStart , inputEnd);
            } else if (this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', inputEnd);
                range.moveStart('character', inputStart);
                range.select();
            }
        }
    });
};

Credits: http://programanddesign.com/js/jquery-select-text-range/

Upvotes: 4

Related Questions