0

Fairly new to JS, trying to build a tool for the company that i work for, that can pull the image from the supplier website when user types in a product number, the code below somewhat works but the image doesn't get replaced when entering a new number.

HTML:

<input id='pCOde' placeholder='Code?'>
<button onclick='addImg()'> Click me </button>
<p id='hImg'></p>

Javascript:

const pCode = document.getElementById("pCode").value;

function addImg() {
    const img = new Image();
    img.src = 'https://SupplierWebsite/pics/' + pCode.value + '.JPG';
    document.getElementById('hImg').replaceWith(img);
    img.style.height = 'auto';
    img.style.width = '85%';
}

Eventually wanted to pull more data from the supplier site, such as product title and price but this seems even trickier.

Filip Seman
  • 1,252
  • 2
  • 15
  • 22
Liiaam93
  • 195
  • 1
  • 2
  • 10
  • I assume `pCode` is an input box. In the 1st line, you are already getting the value, so there is no need of `pCode.value` again in `img.src=...` – TechySharnav May 20 '21 at 09:59

2 Answers2

0

It will help if you can share what kind of value you are hoping to get from pCode. But try using this, it will work.

let pCode = document.getElementById("pCode").value;

function addImg() {
  var img = new Image();
            img.src = 
            `https://SupplierWebsite/pics/${pCode}.JPG`;
            document.getElementById('hImg').replaceWith(img);
            img.style.height = 'auto';
            img.style.width = '85%';
        } 
M.Hassan Nasir
  • 851
  • 2
  • 13
  • pCode - It's a string value usually two or 3 letters followed by a number but i have another problem anyway now, which i don't think can be fixed - not all the images are .JPG some are .jpg instead (and apparently those are different?) – Liiaam93 May 20 '21 at 10:40
  • According to [this](https://stackoverflow.com/questions/41804564/is-there-a-difference-between-jpg-and-jpg) both are same. – M.Hassan Nasir May 20 '21 at 11:03
0

You are already getting .value in let pCode = ... line. So there is no need to pCode.value again, in img.src.

let pCode = document.getElementById("pCode").value;

function addImg() {
  var img = new Image();
  img.src =
    'https://SupplierWebsite/pics/' + pCode + '.JPG';
  document.getElementById('hImg').replaceWith(img);
  img.style.height = 'auto';
  img.style.width = '85%';
}
TechySharnav
  • 4,869
  • 2
  • 11
  • 29