views:

43

answers:

1

Hi Guys, I'm trying to load different images into a DIV according on the selected, something like this:

<select>
  <option value="mercedes">Car #1</option>
  <option value="ferrari">Car #2</option>
  <option value="fiat">Car #3</option>
</select>

If the Car #1 es option is selected, load mercedes.jpg into <div id="car"></div>

Any ideas??

Thanks so much!!

+1  A: 

You can use the .change() event handler, like this:

$("select").change(function() {
  $("#car").html($("<img />", { src: $(this).val() + ".jpg" }));
});

When the value changes, this creates a new <img>, sets its source to NEWVALUE.jpg and uses .html() to set #car's content to that element .html(element) is a shortcut for .empty().append(element).

Nick Craver
Nick thanks for the quick help, but it doesn't seem to work :-|
Alberto
@Alberto - Are you running this on `document.ready`? e.g. inside a `$(function() { });`...if so are these elements being added dynamically?
Nick Craver
Thanks @Nick it worked out great!
Alberto
Nick, do you know how to do if i would like to have a pre selected item and the image loading for this element?
Alberto
@Alberto - That last like, change `});` to `}).change();` to trigger it on-load, then it'll load the currently selected image, is that what you're after? For example you could have an `<option value="pickOne">Please Select</option>` with a `pickOne.jpg`.
Nick Craver
Your a Genius Nick!! Thanks so much, the only thing that doesn't work is navigating trough the list with the arrow keys, but that's not really necesary. I really need to learn more Javascript/jQuery.
Alberto
@Alberto - Unfortunately there's no event fired until a `change` is made (selected), if you use a replacement for your `<select>` (there are a few jQuery plugins out there to do this), they'll *probably* have events, or you can add one easily enough.
Nick Craver