Ex1
Ex1

Reputation: 1

How can I make text into links using jQuery?

I'm trying to make a reply system for the comments on my blog. When someone clicks on "Reply" it will take the comment id and put two brackets infront of it in comment textbox.

Basically it will look like this >>123456789, it's not a link or anything it's just plain text. Once it's been posted the brackets are converted to > so it'll look like this in the final source code: >>123456789 (every id has 9 numbers)

I need to make that text into a link.

Here's what's supposed to happen: http://jsfiddle.net/KFXFd/
Here's what happens when I try to change the class: http://jsfiddle.net/qWYCQ/

Note that the class has to be .commenttext instead of body, but for some reason I can't get it working (I'm terrible at js).

Upvotes: 0

Views: 656

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

You should refer to the current element using this in each loop. You are using thePage in your Fiddle demo which actually contains all the elements having class .commentheader. Try this.

Working demo

(function($) {
    var thePage = $(".commenttext");
    thePage.each(function () {
       $(this).html($(this).html().replace(/(>)(>)[0-9]{9}/ig,
               function(matched) {
                   return "<a href=\"#" + matched.replace(/(&gt;)/g,"") + "\">" + matched + "</a>";})); 
    });
})(jQuery)

Upvotes: 1

Thomas Clayson
Thomas Clayson

Reputation: 29925

Here is working javascript:

$(document).ready(function(){
    var thePage = $(".commenttext");

    thePage.each(function () {
        $(this).html($(this).html().replace(/&gt;&gt;([0-9]{9})/, "<a href=\"#$1\">$1</a>"));
    });
});

There are various problems with your code.

first is that you need to use $(this) within jquery's each() in order to reference the acctual element you're dealing with at the time.

Secondly I've changed your replace(). The ()s around things in regex grab a match which you can reference in the next argument using $1 (or $2 etc... $1 is the first $2 the second $3 the third match, etc).

Hope this makes sense.

Upvotes: 0

Related Questions