3

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, "&nbsp"));
        }
    }
    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.

pv619
  • 409
  • 11
  • 29

3 Answers3

4

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.

André DS
  • 1,823
  • 1
  • 14
  • 24
2

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 
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    Thank you for the answer @Mamun and for vital information. It helped me to understand it better and also thank you for the update. Have a great day bro :) – pv619 Oct 18 '18 at 10:12
  • also thanks @Rory for pointing it out :) and have a great day bro :) – pv619 Oct 18 '18 at 10:13
  • 1
    Thank you once again @Mamun for updating the answer and making the code more efficient bro :) – pv619 Oct 18 '18 at 10:51
  • 1
    @pv619, glad that it makes sense to you :) – Mamun Oct 18 '18 at 10:54
1
$("img#target").attr("src", "images/"+$("#block1").html());
evgeni fotia
  • 4,650
  • 3
  • 16
  • 34