1

I am trying to figure out how I can dynamically display a link in the href of an html a tag. I currently have the below code that displays the values as I type but I would like to have this code display a click url in the a tag href.

Can someone please help?

HTML form code:

<input type="text" id="testTextareadestinationurl" autocomplete="off" size="57" maxlength="2500" name="destinationurl" class="required"/>
<span id='UrlDestinationurl'><?php echo  $destinationurl;?></span>
<a href="" target="_blank"><img src=""></a>

javascript code:

var testTextareadestinationurl = document.getElementById('testTextareadestinationurl');
testTextareadestinationurl.onkeydown = updateUrlDestinationurl;
testTextareadestinationurl.onkeyup = updateUrlDestinationurl;
testTextareadestinationurl.onkeypress = updateUrlDestinationurl;
function updateUrlDestinationurl() {
    document.getElementById('UrlDestinationurl').innerHTML = this.value || "";
}

function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
}
1
  • Assign an id to your <a> tag and set it's src attribute to whatever link you want. Jquery would make this easy Commented Sep 12, 2013 at 3:02

1 Answer 1

2

You're basically missing this from your updateUrlDestinationurl function:

document.getElementById('anchorUrlDestinationurl').href = "http://" + this.value || "";

Assuming you give an id of 'anchorUrlDestinationurl' to your target <a> element.

Don't prepend "http://" depending on what you want to type into the input.

Here's a fiddle.

P.S. you don't need to handle all three of those keypress events but I assume your code is a subset of something...

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

2 Comments

Thank you. Let me give that a try.
Plymouth223 when i submit my form and click on the url link the link doesnt seem to work correctly. I have to delete some characters and retype the url in order for the image to click to the url. Any idea how i can fix that? I can try to provide my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.