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

How to use a value as a name of a file?

I’m a newbie in JS. I want to change the background image of a div by using values from tag. I can change the background-color but now I want to use the value as the name of a jpg file. Does anyone know how? The values will be 1,2,3 and the name of the graphic files are 1.jpg, 2.jpg and 3.jpg.

   <div class="container" id="wrapper">
      <form>
        <label for="my-select">Choose the continent:    </label>
        <select
          name=""
          id="my-select"
          value="Choose the continent"
          onChange="myFunction()"
        >
          <option value="default">default</option>
          <option value="1">Asia</option>
          <option value="2">Australia</option>
          <option value="3">South america</option>
        </select>
      </form>
    </div>
  const myWrapper = document.querySelector("#wrapper");

  function myFunction() {
  var x = document.getElementById("my-select").value;
  myWrapper.style.backgroundImage = url("images/x.jpg");
  }
  // I know the last line won't work. 

>Solution :

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

You were close, try something like this:

  const myWrapper = document.querySelector("#wrapper");

  function myFunction() {
  var x = document.getElementById("my-select").value;
  myWrapper.style.backgroundImage = "url(images/" + x + ".jpg)";
  }
   <div class="container" id="wrapper">
      <form>
        <label for="my-select">Choose the continent:    </label>
        <select
          name=""
          id="my-select"
          value="Choose the continent"
          onChange="myFunction()"
        >
          <option value="default">default</option>
          <option value="1">Asia</option>
          <option value="2">Australia</option>
          <option value="3">South america</option>
        </select>
      </form>
    </div>

If you want even more readable code, you can use template literals instead of string concatenation, like this:

myWrapper.style.backgroundImage = `url(images/${x}.jpg)`;
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