1

I want to convert plaintext to link for an input I have. The HTML code is:

<input type="text" value="http://www.test.com" id="url">

So each time this input with this id is on the page converted to clickable link to open in new page.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220

3 Answers3

2
var href = $('#url').val();
$('#url').replaceWith('<a href="' + href + '">click text</a>')
Ram
  • 143,282
  • 16
  • 168
  • 197
0

Something like this:

var $el = $("#url"),
    url = $el.val();

$el.replaceWith( $("<a />").attr({"href":url,"target":"_blank"}).html(url) );

Place that in a document ready handler or in a script block at the end of the body.

You didn't say what you wanted the text of the link to be so I've just repeated the url as shown in this working demo: http://jsfiddle.net/khJx2/1/

Specifying the "target" attribute as "_blank" will open the link in a new page (or tab, depending on the browser). Remove that to have it open in place of the current page.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • yes, it's perfect but i have another problem now, you see this input should be edit inline ajax and a link in the same time, now it's a link and the edit inline doesn't appear anymore, can you help me please ? –  Jun 18 '12 at 12:18
  • Well that's a different requirement to what you asked about in the original question. Sorry, I don't have time to update my answer now, but I would suggest that your proposed behaviour is non-standard and confusing to users - better to put a button or link next to the text input. – nnnnnn Jun 18 '12 at 20:11
0

IDs must be unique. If you have more than twice the same ID, you're doing something wrong.

What you're looking for are classes.

Here is a sample:

<input type="text" value="http://some.url" class="url">

And the jQuery code (way less complex than the others answers):

$( '.url' ).on( 'click', function() {
    window.open( this.value );
} );

PS: thanks to this answer for the "similar to _blank" code.

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • it's working but not quite good, because when you click inside the input it clicks the link and open a new page, want this to happen only if you click on the text, else if you click on the input or double click on the text shoud make the edit, can you help me ? –  Jun 18 '12 at 13:00