0

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!!"); } }); }); 
9
  • How is your code being executed? Like what is this? Commented Aug 12, 2013 at 20:34
  • 1
    find() looks for elements below the DOM node you're currently in (in this case, $(this) refers to your last a.btn.btn-large.btn-info link). You want to use .closest() instead Commented Aug 12, 2013 at 20:34
  • 3
    Why would you do that anyway? An id is unique on the page. Commented Aug 12, 2013 at 20:34
  • listen to a combination of the two comments above this. You should never have two elements with the same id, so whatever.find('#send_message') should always been the same as $('#sendMessage') Commented Aug 12, 2013 at 20:41
  • ^ provided that whatever is a parent of the element whose id is sendMessage. Which it isn't here. So i kinda worded that wrong haha Commented Aug 12, 2013 at 20:42

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I think I figured it out: $('#message').on("click", "a", function() sets this to be just 'a' elements. obviously textarea is not included in that - sorry - Bill

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.