0

I have several pages that contain dynamic controls. This means I never know which types or how many controls I have on a page. I need a script that selects the text out of a text area when it is clicked. I was thinking the below script would work but it doesn't seem to be functioning as expected.

$(function () {
    $('input[type=textarea]').focus(function () {
        inputValue = this.value;
    });
});


<div style="display: table;">
    <div style="display: table-row">
        <div style="display: table-cell;">
            <span style="font-weight: bold">TextArea 1</span>
        </div>
    </div>
    <div style="display: table-row">
        <div style="display: table-cell;">
            <textarea id="txtTextArea1" rows="3" cols="30">
nsmanners
  • 33
  • 1
  • 6

2 Answers2

0

If you are talking about selecting all the text in a textarea on focus, this has already been answered here.

how to select all text in textarea on focus (in safari)

Community
  • 1
  • 1
Tom Bowers
  • 4,951
  • 3
  • 30
  • 43
0

That won't work because you're binding an event to an element that doesn't necessarily exist in the DOM. To do that, you should use $.on() to bind that and it will work for whenever the element shows up in the DOM. See http://api.jquery.com/on/

For what you want to do:

$(function () {
    $('.container-element').on('focus', 'textarea', function () {
        var inputValue = $(this).val();
    });
});

Please note that to bind events to a future element, you have to provide a selector as a parameter of $.on(). This assumes that you have the following structure:

<div class="container-element">
  <textarea name="some_texarea"></textarea>
</div>

Also note that textarea is a tag on its own not a type of input.

Jazzuzz
  • 490
  • 6
  • 12
  • Should that be var inputValue = $(this).val(); – Ceres Oct 11 '13 at 16:05
  • This doesnt seem to work because I am not using a class for the div. I added the html markup to my question. – nsmanners Oct 11 '13 at 16:38
  • @nsmanners You'll need an identifier of some sort if you want to delegate the behavior to a DOM element that doesn't exist. You could as well add it to the body with `$('body').on('focus ...` but that wouldn't be the most efficient. Simplest is to add a class or ID to the wrapping div and use that for your `$.on()` – Jazzuzz Oct 14 '13 at 19:01