Skip to content Skip to sidebar Skip to footer

Javascript: Displaying Image According To Select Box Value

In my program I have created select box and button. upon selecting different value from select box image should be displayed as shown in expected output. There are two buttons prev

Solution 1:

There are a few tiny errors all adding up to this not working, I'll try to remember and point them out. Here is a working example with only 2 images -you can fill yours back in

  1. you have a div for your image "holder" this should be an <img /> tag
  2. var imgLen = imageObj.length; should be var imgLen = images.length; use the length of your array not the obj.
  3. preBtn.addEventListener should be btnPre.preBtn doesn't exist
  4. holder.src = images[0] + "<br>" + " Women's coat"; the src attribute needs to be a valid url and you mess that up when you append <br> and a string to it.
  5. imageObj.src=images[i]; needs to reference your "holder" not imageObj so it should be document.getElementById("holder").src = images[i];
  6. You don't need to dynamically put the next and previous buttons each image load (you aren't even clearing them) so the DOM keeps piling up with buttons.
  7. You should use numbers as values so you can set the select to the correct description on next and prev
  8. you need to keep track of i when the user jumps on the select (set i on the select change)

// countervar i = 0;

// create object
imageObj = newImage(128, 128);

// set image list
images = newArray();
images[0] = "https://cdn-image.myrecipes.com/sites/default/files/summer-sweet-lemonade-cl.jpg";
images[1] = "http://www.greatamericancookies.com/app/themes/greatamericancookies/library/images/home/carousel3.png";
images[2] = "final_images/ktoys.jpg";
images[3] = "final_images/mixture.jpeg";
images[4] = "final_images/earing.jpg";

var imgLen = images.length;

var go = document.getElementById('go');
var select = document.getElementById('selectBox');
var desc = document.getElementById('desc');
go.addEventListener("click", loadItem);

functionloadItem() {
  var holder = document.getElementById("holder");

  if (document.getElementById('selectBox').value == 0) {
    holder.src = images[0];
    desc.innerHTML = document.getElementById("select0").getAttribute("data-desc");
    i = 0;
  } elseif (document.getElementById('selectBox').value == 1) {
    holder.src = images[1];
    desc.innerHTML = document.getElementById("select1").getAttribute("data-desc");
    i = 1;
  } elseif (document.getElementById('selectBox').value == 2) {
    holder.src = images[2];
    desc.innerHTML = document.getElementById("select2").getAttribute("data-desc");
    i = 2;
  } elseif (document.getElementById('selectBox').value == 3) {
    holder.src = images[3];
    desc.innerHTML = document.getElementById("select3").getAttribute("data-desc");
    i = 3;
  } elseif (document.getElementById('selectBox').value == 4) {
    holder.src = images[4];
    desc.innerHTML = document.getElementById("select4").getAttribute("data-desc");
    i = 4;
  }
  document.getElementById('prev').style.display = "";
  document.getElementById('next').style.display = "";
}

functionnxt() {
  if (i < imgLen - 1) {
    i++;
  } else {
    i = 0;
  }
  select.value = i;
  desc.innerHTML = document.getElementById("select" + i).getAttribute("data-desc");
  document.getElementById("holder").src = images[i];
}

functionprvs() {
  if (i > 0) {
    i--;
  } else {
    i = imgLen - 1;
  }
  select.value = i;
  desc.innerHTML = document.getElementById("select" + i).getAttribute("data-desc");
  document.getElementById("holder").src = images[i];
}
body {
  background-image: url("final_images/back.jpg");
}

img {
  width: 200px;
}

.container {
  /*width: 600px;*//*height: 200px;*/border: inset;
  background-color: rgba(255, 234, 134, 0.9);
}

#selectBox {
  margin-left: 210px;
  width: 160px;
}

#below_hr {
  width: 600px;
  background-color: #ffffff;
}

#preBtn {
  margin-left: 170px;
  margin-top: 170px;
}
<divclass='container'id="main"><formname="myForm"><selectname="mySelect"id="selectBox"><optionid="select0"data-desc="a womans coat"value=0>Women's coat</option><optionid="select1"data-desc="a mens winter coat"value=1>Men's coat</option><optionid="select2"data-desc="a kids toy to play with"value=2>Kid's toys</option><optionid="select3"data-desc="a classic mixture"value=3>Classic mixture</option><optionid="select4"data-desc="a beautiful gold earing"value=4>Gold Earing</option></select><INPUTTYPE="button"VALUE="Go"id="go"></INPUT></form><HRsize="4"color="red"id="hr"><imgid="holder" /><br/><spanid="desc"></span><br/><br/><buttonid="prev"onclick="prvs()"style="display:none">Previous</button><buttonid="next"onclick="nxt()"style="display:none">Next</button></div>

Solution 2:

You have quite a few errors inside your code, Andrew (+1 for that) already listed them in his answer. But i think you maybe should also try to be more dynamic and create the selection from for example a configuration object.

Here's an example:

// CLASSvarImageSelector = (function(doc) {
  // private variablesvar _config,
      _selectionEl, 
      _imageEl,
      _prevBtnEl,
      _nextBtnEl,
      _currentIndex = 0;
  
  // constructorfunctionImageSelector(config) {
    var imageholderEl = doc.querySelector(config.imageholder);
    _config = config;
    _selectionEl = doc.querySelector(config.selection);
    _prevBtnEl = doc.querySelector(config.prevBtn);
    _nextBtnEl = doc.querySelector(config.nextBtn);
    if(!_selectionEl || !imageholderEl) {
      thrownewError('no selection or imageholder element found');
    }
    _imageEl = newImage();
    imageholderEl.appendChild(_imageEl);
    _generateSelection();
    _bindEvents();
  }
  
  // private methodsfunction_generateSelection() {
    var fragment = doc.createDocumentFragment();
    var items = _config.items;
    
    for(var i = 0; i < items.length; ++i) {
      var item = items[i];
      var option = doc.createElement('option');
      option.value = item.value;
      option.textContent = item.name;
      fragment.appendChild(option);
    }
    _selectionEl.appendChild(fragment);
    _selectionEl.selectedIndex = _currentIndex;
  }

  function_loadImage() {
    var items = _config.items;
    var item = items.find(itm => itm.value === _selectionEl.value);
    _imageEl.src = item.image;
    _prevBtnEl.style.display = null;
    _nextBtnEl.style.display = null;
  }
  
  function_bindEvents() {
    var goBtnEl = doc.querySelector(config.goBtn);  
    _selectionEl.addEventListener('change', _loadImage);
    if(_prevBtnEl) {
      _prevBtnEl.addEventListener('click', ImageSelector.prototype.prev);
      _prevBtnEl.style.display = 'none';
    }
    if(_nextBtnEl) {
      _nextBtnEl.addEventListener('click', ImageSelector.prototype.next);
      _nextBtnEl.style.display = 'none';
    }   
    goBtnEl && goBtnEl.addEventListener('click', _loadImage)
  }
  
  function_changeIndex(direction) {
    var length = _config.items.length;
    _currentIndex = (_currentIndex + direction) % length;
    if(_currentIndex < 0) _currentIndex = length -1;
    _selectionEl.selectedIndex = _currentIndex;
    _selectionEl.dispatchEvent(newEvent('change'));
  }
  
  // public methodsImageSelector.prototype.next = function() {
    _changeIndex(1);
  }

  ImageSelector.prototype.prev = function() {
    _changeIndex(-1);
  }

  returnImageSelector;
})(document);


// CONFIGURATIONvar config = {
  selection: '#selectBox',
  imageholder: '#holder',
  goBtn: '#go',
  prevBtn: '#prev',
  nextBtn: '#next',
  items: [
    { name: "Women's coat", value: "womens", image: "https://thumb7.shutterstock.com/display_pic_with_logo/562036/116906134/stock-photo-portrait-of-brown-eyed-cat-isolated-on-white-background-116906134.jpg" },
    { name: "Men's coat", value: "mens", image: "https://thumb1.shutterstock.com/display_pic_with_logo/154447/235089946/stock-photo-cute-little-red-kitten-sleeps-on-fur-white-blanket-235089946.jpg" },
    { name: "Kid's toys", value: "kids", image: "https://thumb9.shutterstock.com/display_pic_with_logo/2288597/574871668/stock-photo-brown-cat-playing-relaxed-on-the-mobile-574871668.jpg" },
    { name: "Classic mixture", value: "mixture", image: "https://thumb9.shutterstock.com/display_pic_with_logo/4363153/520870675/stock-photo-lovely-cat-in-human-hands-vintage-effect-love-for-the-animals-520870675.jpg" },
    { name: "Gold Earing", value: "earing", image: "https://thumb9.shutterstock.com/display_pic_with_logo/428239/454556905/stock-photo-happy-scottish-kitten-looking-at-camera-isolated-on-white-background-454556905.jpg" }
  ]
}

// INITIALISATIONvar selector = newImageSelector(config);
body {
  background-image: url("final_images/back.jpg");
}

img {
  width: 200px;
}

.container {
  /*width: 600px;*//*height: 200px;*/border: inset;
  background-color: rgba(255, 234, 134, 0.9);
}

#selectBox {
  margin-left: 210px;
  width: 160px;
}

#below_hr {
  width: 600px;
  background-color: #ffffff;
}

#preBtn {
  margin-left: 170px;
  margin-top: 170px;
}
<divclass='container'id="main"><formname="myForm"><selectname="mySelect"id="selectBox"></select><inputtype="button"value="Go"id="go" /></form><hrsize="4"color="red"id="hr" /><divid="holder"></div><buttonid="prev">Previous</button><buttonid="next">Next</button></div>

Post a Comment for "Javascript: Displaying Image According To Select Box Value"