Using selections to switch images

I am new to jQuery and I am trying to toggle the image attribute by srcgetting links from an selectHTML tag .

This is the selected HTML that I use:

<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 a jQuery script that I am trying to use to switch the image attribute src:

<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 I'm 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.

+3
source share
2 answers

Do it:

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

When purchasing code with $(function() {...});, make sure that the DOM is loaded before it runs. This is a shortcut to calling the jQuery method .ready().

<select> change, , .

0

$(this).val()

val()
+2

Source: https://habr.com/ru/post/1762060/


All Articles