4

I'm trying to use JS to dynamically replace an image on a page based upon the value of the selected option of a select dropdown. Everything in the code I've included below works perfectly. My "selected_text" variable is properly pulling the value of the selected option in my select dropdown, but I need to somehow write that value to the replacement img src path.

IE: If someone selects "Audi" from my select dropdown, I want to write "Audi" where I have "[selected_text]" in my replacement img src path.

Any ideas?

<script type="text/javascript">
function popmake() {
    var w = document.vafForm.make.selectedIndex;
    var selected_text = document.vafForm.make.options[w].text;
    document.getElementById('make-image').src="/path/to/images/[selected_text].jpg";
}
</script>

3 Answers 3

6

what about

document.getElementById('make-image').src="/path/to/images/" + selected_text + ".jpg";
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I knew it'd be something simple like this. I'm still learning so thank sfor your help!
4

It's simple as string concatenation:

document.getElementById('make-image').src="/path/to/images/"+selected_text+".jpg";

Comments

0

Well, you could have that string somewhere like:

var path_to_images = "/path/to/images/[selected_text].jpg";

... code ...

var selected_text = document.vafForm.make.options[w].text;

document.getElementById('make-image').src = path_to_image.replace("[selected_text]", selected_text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.