William
William

Reputation: 31

jQuery get value from select then change css of a div

I've been trying to use this example but for the life of me I cannot get it working.
Change background of Div from select

Any input to help me get moving along will be very appreciated

<script>
#changemybg {
       background: url(images/default.jpg) no-repeat 50% 50%;
}
</scipt>

<div id="changemybg"></div>

<select name="change" id="backgrounds">
<option>bg</option>
<option>bg1</option>
<option>bg2></option>
</select>

bg = background.jpg
bg1 = background1.jpg
bg2 = background2.jpg

Upvotes: 3

Views: 5820

Answers (2)

alex
alex

Reputation: 490333

The way you were storing the mappings wasn't very flexible. I have stored them as an object.

If you named them bg, bg2, etc, and didn't scope them, you'd need to access them as window['bg' + i] which is messy.

var bg = {
  'bg': 'background.jpg',
  'bg1': 'background1.jpg',
  'bg2': 'background2.jpg' 
};

$('#backgrounds').change(function() {
   var background = $(this).find('option:selected').text();

   if ( ! background in bg) {
       return;
   } 

   $('#changemybg').css({
      'backgroundImage': 'url(' + bg[background] + ')'
   });
});

jsFiddle.

Alternatively, you could store the filename in the value attribute of each option element and simply assign the backgroundImage to $(this).val().

Also, you are trying to set styles inside a script element. That won't work; what you want is a style element.

Upvotes: 5

DJafari
DJafari

Reputation: 13545

Test Below Code :

$("#backgrounds").change(function()
{
    var val = $(this).val();
    $("#changemybg").css("background-image",val);
});

and Change your select to this :

<select name="change" id="backgrounds">
<option value="background1.jpg">bg</option>
<option value="background2.jpg">bg1</option>
<option value="background3.jpg">bg2></option>
</select>

Upvotes: 3

Related Questions