dbomb101
dbomb101

Reputation: 423

Using select to switch images

I'm fairly new to jQuery and I am trying to switch image src attribute by getting the links from a select HTML tag.

This is the select HTML that I'm using:

<select id="pages">
  <option value="Manga/Naruto/Friends/01.png">1</option>
  <option value="Manga/Naruto/Friends/02.png">2</option>
  <option value="Manga/Naruto/Friends/03.png">3</option>
  <option value="Manga/Naruto/Friends/04.png">4</option>
</select>

This is the jQuery script that I'm trying to use in order to switch the image src attribute :

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  $("#pages").change(function(){
    $('#greatphoto').attr('src', val());
    //.val());
  }); 
</script>

And this is the placeholder for the images that I am trying to switch:

<div id="mangaImages">
  <img id="greatphoto" src="Manga/Naruto/Friends/01.png" />
</div> <!-- end of mangaImages -->

Any help with this would be greatly appreciated.

Upvotes: 3

Views: 307

Answers (2)

user113716
user113716

Reputation: 322492

Do this:

$(function() {
   $("#pages").change(function(){
      $('#greatphoto').attr('src', this.value); // Could use $(this).val() too.
   });
});

Wrapping your code with $(function() {...}); makes sure that the DOM is loaded before it runs. This is a shortcut for calling jQuery's .ready() method.

Right now your <select> is not getting the change event, because it doesn't exist yet when the code is running.

Upvotes: 0

babtek
babtek

Reputation: 944

You might try

$(this).val()

instead of

val()

Upvotes: 2

Related Questions