user1592380
user1592380

Reputation: 36205

Difficulty getting value of textarea using jquery

I have the following:

<div class="tab-pane" id="message">
    <textarea rows="4" cols="50" id="send_message" placeholder="Enter text ...">  </textarea>
    <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">OK</a>
    <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">Cancel</a>

when I add:

if($(this).is(":contains(Cancel)"))  {

    var text= $("#send_message").val();

    log.console(text)

I get the correct value

If I change the line to:

    var text= $(this).find("#send_message").val();

I get undefined logged to console. Why is this?

Here is the full jQuery function:

$(function(){
    $('#message').on("click", "a", function(){

        if( $(this).is(":contains(OK)") ) {

            console.log("im in OK!!");
        }
        else if( $(this).is(":contains(Cancel)") )  {

        //  var text= $("#send_message").val();
            var text= $(this).find("#send_message").val();
            console.log(text);
            console.log("im in cancel!!");
        }
    });
});

Upvotes: 0

Views: 128

Answers (2)

Sergio
Sergio

Reputation: 28837

The problem here is that .find() Gets the descendants of each element

Description: Get the descendants of each element in the current set of matched
elements, filtered by a selector, jQuery object, or element.

That means you are clicking in a <a> that is after the <textarea> in the DOM, so .find() will not look for it backwards.

Anyway to find a element who has ID you need just $("#send_message"), and .val() to get its value.

Demo here

Upvotes: 1

federicot
federicot

Reputation: 12331

Make sure you're closing your div with id message, and also, use $('#send_message'). There's absolutely no point in using find with an id selector because as you know ids are intended to be unique (otherwise it's invalid HTML).

Quoting the W3C:

A unique identifier for the element. There must not be multiple elements in a document that have the same id value.

Upvotes: 1

Related Questions