David David - 1 month ago 5
Javascript Question

jQuery: add hyperlink to image when changing image depending on dropdown selection

This is my code:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
</head>
<body>

<select id="my_select" name="select_name" class="order_form_select">
<option data-img="" value="" disabled selected>Please select&nbsp;↓</option>
<option data-img="1.jpeg" value="first">First</option>
<option data-img="2.jpeg" value="second">Second</option>
<option data-img="3.jpeg" value="third">Third</option>
</select>

<a href=""><img id="order_form_image" src=""></a>

<script>
document.getElementById("my_select").onchange = showFormatImage;
function showFormatImage() {
$("#order_form_image").attr('src', $('select[name=select_name] option:selected').attr('data-img'));
$('#img_src').html($("#order_form_image").attr('src'));
return false;
}
</script>

</body>
</html>


That shows an image depending on dropdown selection. That works very well so far. My goal is to also add a specific hyperlink to that image.

When the user selects "First" an images named
1.jpeg
will get shown. This is like a thumbnail. When the user clicks on this image a new window/tab (target="_blank") shall open and show an image named e.g.
1_big.jpeg
.

Does anybody know how to do that?

Answer

Hello this is a working example, hope it's help

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
</head>
<body>

<select id="my_select" name="select_name" class="order_form_select">
    <option data-img="" value="" disabled selected>Please select&nbsp;↓</option>
    <option data-img="1.jpeg" value="first">First</option>
    <option data-img="2.jpeg" value="second">Second</option>
    <option data-img="3.jpeg" value="third">Third</option>
</select>

<a id="link"  target="_blank" href=""><img id="order_form_image" src=""></a>

<script>
document.getElementById("my_select").onchange = showFormatImage;
function showFormatImage() {
    $("#order_form_image").attr('src', $('select[name=select_name] option:selected').attr('data-img'));
    $('#img_src').html($("#order_form_image").attr('src'));
    $('#link').attr('href','big_'+$('select[name=select_name] option:selected').attr('data-img'));
    return false;
}
</script>

</body>
</html>

Comments