1

I'm working on an assignment that requires the background of the website to change based on the selected dropdown option. ie. If 'NYC' is selected, the background changes to a photo of NYC, where the relative URL of the image is already in CSS.

I am required to add the city options using an array with values 'NYC, SF, LA, ATX, SYD' using a 'for loop' in JS, instead of adding it directly to the HTML. I am also asked to specifically incorporate $.append(), $.attr(), $.val(), $.change() and the if/else if statement in the JS code.

I've tried writing the code from scratch along with help from other sources but the pre-written codes don't work with my specific requirements. I understand the HTML and CSS but I'm still very new to Javascript and JQuery. Enough to know it's wrong. I definitely have not gotten the right code for the 'for loop' or the dropdown menu thus far.

Here is the HTML:

<body>
<header>
    <div class="title">
        <h1>CitiPix</h1>
        <p>Your Cities, Your Pix</p>
    </div>
</header>
    <div class="container">
    <form>
        <select id="city-type">
            <option>Select a City</option>
        </select>
    </form>
    </div>
</body>

This is the JS I have so far:

$(document).ready(function(){

$('.container').click(function(event){
  var cityName = ['NYC, SF, LA, ATX, SYD'];
  $("#city-type").append(var cityName);
  cityBackground(city);
  if (!event.target.matches('#submit-btn')) {
  var dropdowns = document.getElementsByClassName('city-type');
  var i;
  for (i = 0; i < container.length; i++) {
}}}

$('select').change(displayVals);
displayVals();

function displayVals() {
    var cityName = $( "#city-type" ).val();

function cityBackground(citytype){
    if (citytype === 'NYC') 
  {
      $('body').attr('class', 'nyc');
  }
  else if (citytype === 'SF')
  {
     $('body').attr('class', 'sf');
  }
  else if (citytype === 'LA')
  {
     $('body').attr('class', 'la');
  }
  else if (citytype === 'ATX')
  {
     $('body').attr('class', 'austin');
  }
  else if (citytype === 'SYD')
  {
     $('body').attr('class', 'sydney');
  }
  }
}

The dropdown menu is not showing, it just shows the "Select a City" text and the whole dropdown code is not running. The .change and .val requirements are also confusing as to where its suppose to fit in the code.

anniel
  • 15
  • 4

2 Answers2

1

Cycling through a loop

There's actually nothing wrong with your loop, you just aren't doing anything within the loop. You need to add to the select element from within the loop you have defined.

// Cycle through the array
for (i = 0; i < cityName.length; i++) {

  // Code to be repeated for each element goes here

}

Adding to a select

Check this answer for ways of adding options to a select: Adding options to a <select> using jQuery?

In the example below I have used the following line, but there may be some issues in IE that you will need to explore, or use the alternative that the accepted answer suggests.

$("select").append(new Option("text", "value"));

Gathering the select value

You can get the value of a select using .val() - i.e. $("#select").val() will provide the value of the chosen option. You're doing this correctly already.


Manipulating the classes

You can add a class to an element using .addClass("classname");

You can reset all classes by setting the class attribute to a blank string - i.e. .attr("class", ""), or assign classes by providing a second argument instead of an empty string.

Your use of .attr("class", "NYC") is actually allowing you to combine these steps into one command. You're doing this correctly already.


Demo

// Create array of cities
var cityName = ["NYC", "SF"];

// Cycle through the array
for (i = 0; i < cityName.length; i++) {

  // Add options to the select
  $("#city-type").append(new Option(cityName[i], cityName[i]));
  
}



// Add change event to select
$("#city-type").change(function() {

  // Clear classes on the body and assign new value
  $("body").attr("class", $(this).val() );

});
.NYC {
  background: blue;
}

.SF {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <header>
    <div class="title">
      <h1>CitiPix</h1>
      <p>Your Cities, Your Pix</p>
    </div>
  </header>
  <div class="container">
    <form>
      <select id="city-type">
        <option>Select a City</option>
      </select>
    </form>
  </div>
</body>
Oliver Trampleasure
  • 3,293
  • 1
  • 10
  • 25
  • Thank you for clarifying and explaining in such detail! I really appreciate the demo, it seems to work perfectly when I run the code snippet. The dropdown isn't showing on my end, using Visual Studio Code, but I'm sure if I fiddle with it some more I should figure it out! – anniel Jun 15 '19 at 02:42
0

You have several syntax errors in your Javascript, many braces and parentheses aren't closed, some functions are being called before they are declared.

This is a partial solution for your problem: https://jsfiddle.net/jkpdLuho/1/

$(document).ready(function() {
  var places = ['NYC', 'SYD']
  for (i = 0; i < places.length; i++) {
    $('select').append('<option value="' + places[i] + '">' + places[i] + '</option>')
  }

  $('select').on('change', function() {
    $('body').attr("class", this.value)
  })
})

<html>
  <header>
    <div class="title">
      <h1>CitiPix</h1>
      <p>Your Cities, Your Pix</p>
    </div>
  </header>

  <body>
    <form>
      <select id="city-type">
        <option>Select a City</option>
      </select>
    </form>
  </body>
</html>

.NYC {
  background: yellow;
}

.SYD {
  background: pink;
}

I'd recommend using a code editor that correctly indents your code for you (such as using AtomBeautify if you're using Atom), it will make it easier to notice any unclosed statements. When it comes to learning jQuery, it's also good to play around using the browser's dev console to see what effects jQuery commands have on the DOM. You'll for example see that you need to write out the entire HTML element if you do $('select').append('<option>Name</option>').

Lupina
  • 572
  • 4
  • 12
  • Thank you for the explanation! I have to admit the functions confuse me and I should use a better code editor, I'm currently using Visual Studio Code. With the partial code you've provided, I assume I would no longer be needing the if statements? – anniel Jun 15 '19 at 02:45
  • @anniel I'm storing the name of the CSS class in the option's value as so: ``, when the `select` is changed I add that CSS class to the document. You don't have to use an if statement since the option's value and the CSS class name are the same. Visual Studio is a good editor, you can for example install `jslint` and `Beauty` to catch errors. – Lupina Jun 15 '19 at 13:55