Подтвердить что ты не робот

Как выбрать весь текст в textarea на фокусе (в сафари)

Я не могу понять, почему я не могу получить содержимое текстового поля, которое будет выбрано, когда textarea получит фокус.

Пожалуйста, посетите живой пример здесь: http://jsfiddle.net/mikkelbreum/aSvst/1

Используя jQuery, это мой код. (IN SAFARI) Это делает текст выбранным в случае события щелчка, но не фокусным событием:

$('textarea.automarkup')
.mouseup(function(e){
    // fixes safari/chrome problem
    e.preventDefault();
})
.focus(function(e){
    $(this).select();
})
.click(function(e){
    $(this).select();
});
4b9b3361

Ответ 1

Самое простое - объединить существующий код с таймером, поскольку событие focus, как правило, слишком рано в WebKit:

Пример jsFiddle: http://jsfiddle.net/NWaav/2/

код:

$('textarea.automarkup').focus(function() {
    var $this = $(this);

    $this.select();

    window.setTimeout(function() {
        $this.select();
    }, 1);

    // Work around WebKit little problem
    function mouseUpHandler() {
        // Prevent further mouseup intervention
        $this.off("mouseup", mouseUpHandler);
        return false;
    }

    $this.mouseup(mouseUpHandler);
});

Ответ 2

Tim Down ответ заставил меня закрыть, но он все еще не срабатывал при нажатии и перетаскивании в Chrome, поэтому я сделал это (Coffeescript).

$.fn.extend
    copyableInput: ->
        @.each ->
            $input = $(this)

            # Prevent the input from being edited (but allow it to be selected)
            $input.attr 'readonly', "readonly"

            if $input.is 'textarea'
                $input.unbind('focus').focus ->
                    input = $(this).select()
                    $input.data 'selected', true

                    setTimeout ->
                        input.select()
                    , 0

                # Work around WebKit little problem
                $input.bind 'mousedown mouseup', (e) ->
                    $input.select()

                    if $input.data('selected') == true
                        e.preventDefault()
                        return false


                $input.unbind('blur').blur ->
                    $input.data 'selected', false

            else
                # Select all the text when focused (I'm intentionally using click for inputs: http://stackoverflow.com/questions/3150275/jquery-input-select-all-on-focus)
                $input.unbind('click').click ->
                    input = $(this).select();

                    setTimeout ->
                        input.select()
                    , 0

Ответ 3

Это единственное, что работает в Safari. Фокус не будет работать.

<script type="text/javascript">
function SelectAll(id)
{
    document.getElementById(id).focus();
    document.getElementById(id).select();
}
</script>

Textarea:<br>
<textarea rows="3" id="txtarea" onclick="SelectAll('txtarea');" onfocus="SelectAll('txtarea');" style="width:200px" >This text you can select all by clicking here </textarea>

Input TextBox:<br>
<input type="text" id="txtfld" onclick="SelectAll('txtfld');" style="width:200px" value = "This text you can select all" />

Ответ 4

Кажется, что фокусное событие мешает методу select. Назовите его после короткого запаздывания:

<textarea id="ta0" onfocus="
  var inp=this;
  setTimeout(function(){inp.select();},10);
">Here is some text</textarea>

Учитывая это только для справки, возможно, текстовое поле должно быть только для чтения.

Ответ 5

$("textarea").on("focus", function(event) {
  event.preventDefault();
  setTimeout(function() { $(event.target).select(); }, 1); 
});

http://jsfiddle.net/xCrN6/2/

Ответ 6

У меня нет браузера Safari, но у меня была такая же проблема с IE, и я использовал следующие работы:

$(document).ready(function() {
    $('body').delegate('textarea.automarkup', 'focus', function(e) {
        var myText = $(this);
        var mytxt = myText.text();
        myText.text(mytxt + "\n event fired: " + e.type);
        myText.select();
    });
    $('body').delegate('textarea.automarkup', 'click', function(e) {
        var myText = $(this);
        var mytxt = myText.text();
        myText.text(mytxt + "\n event fired: " + e.type);
        myText.select();
    });
});

РЕДАКТИРОВАТЬ: После немного более активного воспроизведения я использовал:

$(document).ready(function(e) {
        $(document).delegate('textarea.automarkup', 'focus click', function(e) {
        var myText = $(this);
        var mytxt = myText.text();
        //myText.text(mytxt + "\n event fired: " + e.type);
        myText.select();
        e.stopImmediatePropagation(); 
        $('#igot').text(mytxt+e.type);
        return false;
    });
});

в этом примере: http://jsfiddle.net/MarkSchultheiss/aSvst/23/