Pascal Boschma
Pascal Boschma

Reputation: 197

jQuery change image when SELECT changes

Hello Stackers,

I'm having a question about jQuery. I have the following code, and I want that if I select one of the options, that the Image SRC changes to that path. (Direct, without any other clicks). Is this possible? (It's a kind of Live Preview of the selected image) I Tried, but it doesn't seem to be working.

The Form and Image Display

 <b>Afbeelding</b><br><select name="choose" id="choose">
                 <?php
                 if ($handle = opendir('C:/inetpub/wwwroot/magieweb/images/news'))
    {   
        while (false !== ($file = readdir($handle)))
        {
            if ($file == '.' || $file == '..')
            {
                continue;
            }   

            echo '<option value="' . $file . '"';

            if (isset($_POST['topstory']) && $_POST['topstory'] == $file)
            {
                echo ' selected';
            }

            echo '>' . $file . '</option>';
        }
    }
    ?>
                   </select><br><br>

                    <ul style="border: 1px solid #2087A1; list-style-type: none; margin-right:40px; min-height:30px;">
            <li><strong style="color:#2087A1; margin-top:3px; margin-bottom:3px;">Nieuwsafbeelding Preview</strong></li>    
            <li><img id="blah" src=""></li>

         </ul><br><br>

My jQuery

$('#choose').change(function(){
           $('#blah').attr('src', this.value);
            alert(this.value);
        });

Thanks in Advance

Upvotes: 0

Views: 4958

Answers (1)

Bmd
Bmd

Reputation: 1318

Updated: retrieves selected option value from select box on change.

$('#my_select_box').change(function(){
	$('#my_changing_image').attr('src', $('#my_select_box').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="my_select_box">
<option value="http://g-ecx.images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg">something</option>
<option value="https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg">something else</option>
</select>

<img id="my_changing_image" src="http://g-ecx.images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg" />

https://jsfiddle.net/hqk1r8fk/1/

Upvotes: 2

Related Questions