If i have a variable lets say
var id = //something dynamically generated
then i have <a href="http://localhost/ (the variable id)"
How do i go about this?
If i have a variable lets say
var id = //something dynamically generated
then i have <a href="http://localhost/ (the variable id)"
How do i go about this?
Share Improve this question asked Oct 14, 2011 at 12:37 user951042user951042 07 Answers
Reset to default 7The concatenation cannot occur within the anchor tag itself, but you can set it like this:
<a id="my_anchor" href=""></a>
<script type="text/javascript">
// jQuery way
$( "#my_anchor" ).attr( 'href', 'http://localhost/' + id );
// Non-jQuery way
document.getElementById( "my_anchor" ).href = 'http://localhost/' + id;
</script>
Suppose:
<a id="yourLink" href="http://localhost/ (the variable id)" />
Plain JavaScript
document.getElementById('yourLink').href += id;
or in jQuery
$('#yourLink').attr('href', function() {
return this.href + id;
});
Nobody has pointed out you should always do encodeURIComponent
when you set things like this; otherwise you leave yourself open to script injection attacks:
Taking @jayp's example:
<a href="#" id="mylink">My Link</a>
var id = getSomethingDynamic();
var url = "http://localhost/" + encodeURIComponent(id);
document.getElementById("mylink").href = url;
Something like this:
<a href="#" id="mylink">My Link</a>
var id = // something dynamic
var url = "http://localhost/"+id;
document.getElementById("mylink").href = url;
You don't have to wait for the document to have fully loaded, in most cases as long as the element has been loaded into the DOM you will be fine assuming that your Javascript is placed after the element (like above).
Not good practice, but it's misleading to say you "have" to wait for the whole page to be loaded. You don't.
Javascript function:
function openUrl(id)
{
window.location = "http://localhost/"+id
}
html:
<a href="javascript:void(0)" onclick="openUrl(id)">link</a>
Try this one, I used this
<script type="text/javascript">
var id = 2; //something dynamically generated
<a href='http://localhost/edit.php?catID "+id+" '>
<script>
You can just retrieve the DOM element, and add something to the href property. Like this:
<script type='text/javascript'>
var id = 5;
window.onload = function()
{
document.getElementById('url').href += id;
}
</script>
<a href='http://localhost/?id=' id='url'>Click me</a>
You have to wait for the document to load in order to get the element, it would not exist otherwise.