Reputation: 15
I am trying to change 2 things, a link and an image, when the user selects an <option>
in a <select>
element.
<select onchange="document.getElementById('pagelink').href = this.link; document.getElementById('image').src = this.value">
<option link="test.html" value="selectedimage.png">Text</option>
<option>Another option</option>
</select>
<a id="pagelink"></a>
<img id="image" src="temp.png"/>
I adapted this technique from this answer.
As you can see, the main problem is that 'link' is a completely made up thing that doesn't work, and as such the link always defaults to "undefined". Unfortunately, I can't have two 'value''s and using 'label' doesn't work.
You might be able to tell that I really don't know a lot about JavaScript. Is there an alternative to 'value' I can use, or a way to define a new, similar element?
Upvotes: 0
Views: 661
Reputation: 28837
Try this:
Use data-link
instead of just link
, its a convention to use data-
. You can use .getAttribute() to retrieve the info inside data-link
.
HTML
<select id="selector">
<option data-link="test.html" value="selectedimage.png">Text</option>
<option data-link="test2.html" value="selectedimage2.png">Text2</option>
</select>
Javascript
document.getElementById('selector').onchange = function () {
document.getElementById('pagelink').href = this.options[this.selectedIndex].getAttribute('data-link');
document.getElementById('image').src = this.value
}
I also removed your inline code and gave a id #selector
to the select. Like this you can have javascript on right place and not in the middle of html.
Upvotes: 3
Reputation: 206218
<select id="select">
<option value="link1,scr1">Text 1</option>
<option value="link2,scr2">Text 2</option>
</select>
<br>
<a id="pagelink" href="#">link</a>
<img id="image" src="temp.png"/>
var d = document,
$sel = d.getElementById('select'),
$plk = d.getElementById('pagelink'),
$img = d.getElementById('image');
$sel.onchange = function(){
var val = this.value.split(',');
alert(val[0]+' '+val[1]);
// $plk.href = val[0];
// $img.src = val[1];
};
Upvotes: 1