TomDev
TomDev

Reputation: 287

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. 

Upvotes: 0

Views: 46

Answers (2)

IISkullsII
IISkullsII

Reputation: 725

Your Solution is mostly correct. You only needed to insert the entire string to the CSS-Styling, as you would normally in CSS.

You then needed to concatenate the X-Value to the string, so it gets the number stored in it instead of the x as a direct character.

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

function myFunction() {
  var x = document.getElementById("my-select").value;

  // You'll need to insert the CSS-Style as an entire string.
  // We concatenate the Variable X to the string, so it gets dynamicly used.
  myWrapper.style.backgroundImage = "url('images/"+x+".jpg')";
} 

Upvotes: 1

cMarius
cMarius

Reputation: 1132

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)`;

Upvotes: 1

Related Questions