Dean J
Dean J

Reputation: 40369

Finding the value/text of an A tag using JQuery

Something's not quite right here.

$(document).ready(function() 
        { 
            $("a#edit").click(function() {
                $("div#search").addClass("hidden");
                $("div#edit").removeClass("hidden");
            alert((this).val());
            return false;
            }); 
        } 
); 

And later:

<a href="#" id="edit">10.1001</a>

I want to get the value "10.1001" from this. alert((this).val()); doesn't seem to work, nor does alert((this).text());. Can someone point out really quickly what I'm missing here? Thanks!

Upvotes: 1

Views: 9122

Answers (3)

James
James

Reputation: 112000

You seem to be forgetting the crucial $ symbol (an alias for jQuery), which when followed by parenthesis ((...)), calls the jQuery constructor and provides all of its methods.

Try:

alert( $(this).text() );

The keyword this actually provides a reference to the DOM element being clicked, and methods like val and text are not implemented on DOMElement. By wrapping a DOM element in a jQuery object you can get access to these methods.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253506

Try:

$(document).ready(function() 
        { 
            $("a#edit").click(function() {
                $("div#search").addClass("hidden");
                $("div#edit").removeClass("hidden");
            alert($(this).text()); // $(this).text() should return the text contained within the relevant tag.
            return false;
            }); 
        } 
);

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630627

Instead of (this).val() you want $(this).text() for anchors.

.val() is for input type elements, .text() is used to get the text within a tag :)

Your code should look like this overall, note the addd $ before (this):

$(function() {
  $("a#edit").click(function() {
    $("div#search").addClass("hidden");
    $("div#edit").removeClass("hidden");
    alert($(this).val());
    return false;
  });
}); 

Upvotes: 4

Related Questions