Guardian413
Guardian413

Reputation: 3

Show image when option is selected

I would like to make a select that when you click an option, an image will show next to the form. Nothing from this needs to be sent to the database, it's just for looks.

I’ve tried searching online but I am only able to find images in the select options, which is not what I’m looking for. I’m also not sure what it should be done with, most likely Javascript. But whatever works would be fine.

Example code (form):

<form>
<select name="optionType">
    <option value="" hidden selected> </option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select><br>
<input type="submit" name="optionAdd" value="submit"><br>

Example outcome picture: 1

Mind you I am not looking for it to show after the submit is clicked but simply when the option is selected. Does anyone know how to do this?

Upvotes: 0

Views: 3329

Answers (1)

Mayur Agarwal
Mayur Agarwal

Reputation: 854

You can try this code:

HTML

<select name="optionType" onchange="renderImage()" id="selectOption">
    <option value="" hidden selected> </option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>
<img id="myImg" src="compman.gif" width="107" height="98">

JS

function renderImage() {
var selected = document.getElementById("selectOption");
var imgUrl = "";
if (selected.value == 1) {
    imgUrl = "https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80";
} else if (selected.value == 2) {
    imgUrl = "https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80";
} else {
    imgUrl = "";
}

document.getElementById("myImg").src = imgUrl;

}

Try this jsfiddle: https://jsfiddle.net/kamyh1tq/

Upvotes: 2

Related Questions