1

I have a javascript function that is getting the values of other html elements and I want to pass those values to the image tag. How do I Pass that?

My Function is below:

<script type="text/javascript">
    function submitValues()
    {
        var firstname = document.getElementsByName("firstname")[0].value;
        var lastname = document.getElementsByName("lastname")[0].value;
    }

<img src="firstname=get_javascript_valuehere;lastname=get_javascript_valuehere;/>
Liam
  • 27,717
  • 28
  • 128
  • 190
Kumar
  • 179
  • 1
  • 6
  • java or javascript? besides, what you have posted is not a function, but a simple dom image element. Edit: the OP edited to java script – briosheje May 06 '15 at 14:47
  • you make no sense, please rephrase your question and please provide some code. – Grumpy May 06 '15 at 14:47
  • 1
    Do you want to alter the `src` attribute in the `img` tag using js? – Nirmi May 06 '15 at 14:51
  • 1
    No, I want to get the entered first name and last name entered in the textbox and pass it to the image tag.. – Kumar May 06 '15 at 14:53
  • 1
    What is "passing it to the image tag" if it is not changing the `src` attribute? Please be more specific. –  May 06 '15 at 14:54
  • 1
    First Name and Last Name entered by the user in the text boxes and I want to pass it to the Img tag.. – Kumar May 06 '15 at 14:56
  • possible duplicate of [Javascript set img src](http://stackoverflow.com/questions/1232793/javascript-set-img-src) – Liam May 06 '15 at 15:00

3 Answers3

2

Put an id on your image tag and use the following:

document.getElementById("myImg").src = "firstname=" + firstname + ";lastname=" + lastname + ";";

That's at least what you've asked for, but I imagine there is more to this question if you'd like to elaborate.

blink-fish
  • 171
  • 17
1

Use jQuery's .attr() method to modify the attribute of an element.

function submitValues() {
    var firstname = $("[name=firstname]").val();
    var lastname = $("[name=lastname]").val();
    $("img").attr("src", "firstname=" + firstname + ";lastname=" + lastname + ";");
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0
function submitValues()
{
    var firstname = document.getElementsByName("firstname")[0].value;
    var lastname = document.getElementsByName("lastname")[0].value;
    var img =  document.getElementById('fullName');
    img.setAttribute("src","firstname"+firstname+"lastname"+lastname+";");      
}

Add an id to the img to query it using the document.getElementById(), then set the src attribute using this code.

It should work.