Reputation: 409
I am trying to get parameter value from the url, add it inside a div and then clone that value inside the img src attribute.
I can get the parameter value inside a div, and get it to clone as well but it's doing it like this:
<img id="target" src="images/">samplevalue.png</img>
I need to do like it this:
<img id="target" src="images/samplevalue.png" />
Sample parameter: param1=samplevalue.png
here's the code:
html
<div id="block1"></div>
<img id="target" src=""/>
jQuery/Javascript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return decodeURIComponent(pair[1].replace(/\+/g, " "));
}
}
return decodeURIComponent(pair[1]);
}
document.getElementById("block1").innerHTML =
getQueryVariable("param1");
$(document).ready(function() {
$("img#target").attr("src", "images/").html($("#block1").html());
});
Even if adding the parameter value straight inside the img src attribute is fine too than adding first inside the div.
Any help on this is highly appreciated. Thank you very much in advance.
Upvotes: 3
Views: 1798
Reputation: 68943
You have to add the returned value from the function as part of the attribute src
.
With .html($("#block1").html())
on the image element, you are trying to set html on th image which is actually invalid:
Change the function to:
$(document).ready(function() {
var urlPart = getQueryVariable();
$("img#target").attr("src", "images/" + urlPart);
});
Please Note:
Since you are already using jQuery, I will suggest you not to mix JavaScript & jQuery if possible, like:
document.getElementById("block1").innerHTML = getQueryVariable("param1");
Could be easily written:
$('#block1').text(getQueryVariable("param1")); //text() is preferred when dealing with text content
Upvotes: 2
Reputation: 1901
You should do it like this :
$(document).ready(function() {
var param1 = getQueryVariable("param1");
$("img#target").attr("src", "images/"+param1);
$("#block1").html(param1);
});
Put your param into a variable and then use it to change your SRC attribute and to put the content into your div.
Upvotes: 4