+ 2

How to make image src dependent on input?

So Im making a program that INVOLVES the user entering an image source and the code displays that. My #1 problem is how to make <img scr=[whatever the userā€™s inputted URL here ].

11th Feb 2018, 2:24 AM
privrax.
privrax. - avatar
9 Answers
+ 5
@Faisal, You can't directly use tag name elements, y.src = x; it's an array. Use following instead y[0].src = x; to set the first occurrence of the tag elements.
11th Feb 2018, 5:06 AM
CalviÕ²
CalviÕ² - avatar
11th Feb 2018, 2:58 AM
BroFar
BroFar - avatar
+ 2
To do this, you may need to use JavaScript. Set a variable to prompt the user for the URL for the website, then set the value of the src attribute for the image as that value. For example: var x = prompt("Enter the URL of the image"); var y = document.getElementByTagName("img"); y.src = x;
11th Feb 2018, 2:46 AM
Faisal
Faisal - avatar
+ 2
Alright. Seems legit. Im not sure I have the HTML right. I simply have <img> in there. The JS should pick up the img tag and change src to user input. However, I get a blank page, so something is obviously going wrong. Is there a way to assign a variable or id to the img element and refer and manipulate it in the JS?
11th Feb 2018, 3:19 PM
privrax.
privrax. - avatar
+ 2
@Faisal Thanks for the help! Works great!
11th Feb 2018, 5:01 PM
privrax.
privrax. - avatar
+ 1
@Faisal Apparently getElementByTagName isnt a function...
11th Feb 2018, 3:24 AM
privrax.
privrax. - avatar
+ 1
@Faisal Lol. Welcome to my world. Thanks though!
11th Feb 2018, 5:27 AM
privrax.
privrax. - avatar
+ 1
You could also just create the img tag directly through JavaScript, which may work a little better. To do this, just use a document.write function with the tag inside of it, just like in HTML. For example: var x = prompt(); document.write("<img src = " + x + "></img>");
11th Feb 2018, 4:11 PM
Faisal
Faisal - avatar
0
@privrax. Uuuuggghhh sorry I can never get that right. The function should be getElementsByTagName, with element being plural.
11th Feb 2018, 3:33 AM
Faisal
Faisal - avatar