RadicalActi
RadicalActi

Reputation: 191

How to replace a href link within a Textarea with jQuery

I have a basic questions with jQuery.

I acutally want to change the "a" tag within a Textarea. I know that "a" tags aren't functioning within a textarea so I can not target them using jQuery selectors.

Example:

<textarea><a href="http://www.google.com"></a></textarea>

I want to change into this:

<textarea><a href="http://www.stackoverflow.com"></a></textarea>

Is there any basic solution for this matter?

EDIT: I forgot to mention that the first link (http://www.google.com) is not a static link. It will always be changing. So I'd need an ultimate solution.

Upvotes: 0

Views: 4237

Answers (4)

Ken Bellows
Ken Bellows

Reputation: 6942

Using a quickly slapped together Regular Expression to act on all link-like patterns in the textarea, this will probably do what you want, though without more context it's tough to tell for sure:

var new_url = "www.stackoverflow.com";
var text = $('textarea').html();
$('textarea').html(text.replace(/(&lt;a [^&]*href=['"])[^'"]*(['"][^&]*&gt;)/, "\$1"+new_url+"\$2"));

See it in action here: http://jsfiddle.net/JaTAr/2/

This will look for anything in the textarea that has the pattern <a ...href='...'...> and replaces it with <a ...href='www.stackoverflow.com'...>. So depending on your content, it may be fussy, but probably it will do what you want.

Upvotes: 1

Tom
Tom

Reputation: 4180

This is an example; after loading the href will get replaced:

<!DOCTYPE html>
<html>
    <head>
        <script>
                window.onload = function () {
                    var textarea = document.getElementsByTagName("textarea")[0];
                    textarea.innerHTML = 
                        textarea.innerHTML.replace(
                            /href=".*"/, 
                            "http://www.stackoverflow.com");
                }
        </script>
    </head>
    <body>
         <textarea><a href="http://www.google.com"></a></textarea>
    </body>
</html>

Upvotes: 3

DevlshOne
DevlshOne

Reputation: 8457

var txt = $('textarea').text();
var ancStart = txt.toString().indexOf('<a');
var ancEnd = txt.toString().indexOf('a>') + 2;
var sl = (ancStart * -1) + ancEnd;
var newTxt = txt.slice(sl);
newTxt += '<a href="http://www.stackoverflow.com"></a>';
$('textarea').empty().text(newTxt);

jsFiddle DEMO

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20747

What if you were to get the content of the textarea, put it inside an invisible div, use jquery selectors inside the div to make your changes, and then re-fill the textarea with the new content.

HTML:

<div style="display:none;"></div>
<textarea><a href="http://www.google.com"></a></textarea>

jQuery:

$('div').html($('textarea').val());
$('div').find('a').attr('href', 'http://www.stackoverflow.com');
$('textarea').val($('div').html());

Upvotes: 2

Related Questions