Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript function print var in div

Trying to pass a variable to a function as a parameter of my function and have this function print the value of a global variable in a specific

var desc1 = "apple description";
var desc2 = "bananna description";
var desc3 = "orange description";


  function showDesc(arg) {
    var myDesc = arg;
    document.getElementById('description').innerHTML = myDesc; 
  }
<div onclick="showDesc('desc1')">Apples</div>
<div onclick="showDesc('desc2')">Bannans</div>
<div onclick="showDesc('desc3')">Oranges</div>

<div id="description"></div>

Trying to make the value of desc1 show in when clicking on Apples, and show value of desc2 and likewise.

Currently, it is only printing "desc1" when clicking on "Apples" and "desc2" when clicking on "Bananas"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are passing the ‘desc1’ and ‘desc2’ etc as strings into the function – you need to consider these as references. The easiest way is to create an object literal and use the passed in argument to select the chosen description from the object literal.

Also – you should be using buttons to handle the clicks –

const descriptions = {
  apple: "Apple description",
  banana: "Bananna description",
  orange: "Orange description"
}


  function showDesc(type) {
    document.getElementById('description').innerHTML = descriptions[type]; 
  }
<button type="button" onclick="showDesc('apple')">Apples</button>
<button type="button" onclick="showDesc('banana')">Bannans</button>
<button type="button" onclick="showDesc('orange')">Oranges</button>

<hr/>

<div id="description"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading