Ian Indratama
Ian Indratama

Reputation: 7

javascript parameters reference errors

i was trying to make a photo gallery where user can click the link and show different photo but itry to put the parameters as a name but it keeps getting error says that said reference error but when i try to use number like 0,1,2,3,4,5 everything goes normal exactly like i want.My question is how to make the parameters to be a name instead of a number ?

  <body>
<img src="../bab2/images/Gusion.png" width="400px" alt="" id="gambar">
<a href="#" onclick="ganti(gusion)">1</a>
<a href="#" onclick="ganti(selena)">2</a>
<a href="#" onclick="ganti(2)">3</a>
<a href="#" onclick="ganti(3)">4</a>
<a href="#" onclick="ganti(4)">5</a>
<script type="text/javascript">
  function ganti(nama){
    var lokasi = '../bab2/images/' + nama + '.png';
    document.getElementById('gambar').src =lokasi;
  }
</script>

Upvotes: 0

Views: 40

Answers (2)

Tejas Chandrashekhar
Tejas Chandrashekhar

Reputation: 81

If you want to pass names as parameters you need to pass them as Strings, i.e., enter the name within quotes. Here is the modified code:

<a href="#" onclick="ganti('gusion')">1</a>
<a href="#" onclick="ganti('selena')">2</a>

Upvotes: 0

Quentin
Quentin

Reputation: 943537

gusion and selena are names… specifically, they are variable names.

If you want a string then you need to surround it with quotes.

Upvotes: 1

Related Questions