How to change the background of a div using the select tag and javascript?

I found an answer to my question here but it really doesn't work for me. I am very new to programming and quite not yet familiar using javascript. Sad to say, I've been trying to do this for quite a while.

What I want to do is to change the background of a div whenever I change the option in a select tag. Here's my .JSP code

Add Ons Type:
<select id="addOnsType" name="addOnsType" onchange="changePicture()">
    <option selected disabled> select add ons</option>
    <c:forEach var="addOnsType" items="${addOnsType}">
        <option value="${addOnsType.addOnsTypeId}"> ${addOnsType.description} </option>

<div id="PictureDiv" style="height: 58px; width: 344px">

The addOnsTypeId has values of 1, 2 and 3.

While my javascript is written as (I've used what I saw in here)

function changePicture() {

    var PictureDivBG = document.getElementById("PictureDiv");
    var addOnsTypeSelected = document.getElementById("addOnsType");

    if (addOnsTypeSelected.val() == 1) { = "url('../images/cartoon1.jpg')";
    } else if (addOnsTypeSelected.val() == 2) { = "url('../images/cartoon2.jpg')";
    } else if (addOnsTypeSelected.val() == 3) { = "url('../images/cartoon3.jpg')";


Any help/hints/answers would be much appreciated. Thanks!

Follow up newbie question: I'm quite confused about javascript and jQuery, what's the difference?

Answers 1

  • addOnsTypeSelected is a dom element reference, it doesn't have the val() function, which is provided by jQuery.

    You can get the jQuery object for those element using the id selector and get the value

    function changePicture() {
      var addOnsTypeSelected = $("#addOnsType").val(),
      if (addOnsTypeSelected == 1) {
        backgroundImage = "url('../images/cartoon1.jpg')";
      } else if (addOnsTypeSelected == 2) {
        backgroundImage = "url('../images/cartoon2.jpg')";
      } else if (addOnsTypeSelected == 3) {
        backgroundImage = "url('../images/cartoon3.jpg')";
      $('#PictureDiv').css('background-image', backgroundImage);

    But using jQuery event handlers, you can

    jQuery(function() {
      var imgs = {
        1: 'url(//',
        2: 'url(//',
        3: 'url(//'
      $('#addOnsType').change(function() {
        $('#PictureDiv').css('background-image', imgs[$(this).val()] || 'none');
    <script src=""></script>
    Add Ons Type:
    <select id="addOnsType" name="addOnsType">
      <option selected disabled>select add ons</option>
    <div id="PictureDiv" style="height: 58px; width: 344px">

Related Articles