最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Dynamic JavaScript Image SRC Path Replacement - Stack Overflow

programmeradmin3浏览0评论

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>

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>
Share Improve this question edited Jul 16, 2010 at 16:52 Bill the Lizard 406k211 gold badges572 silver badges889 bronze badges asked Jul 8, 2010 at 20:58 aegenesaegenes 1,0613 gold badges14 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

what about

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

It's simple as string concatenation:

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

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);
发布评论

评论列表(0)

  1. 暂无评论