-1

Okay so I'm working on a project where I have to output a cat image that resembles a letter in the alphabet depending on what letter the user types into the input box. So for example if a is typed in then a image of a cat that looks like an a will be displayed. I have to implement fromcharcode into my javascript, but I'm not sure how to actually go about doing this. Any help would be great. Thanks.

seanrs97
  • 323
  • 3
  • 14
  • Why would you need `fromCharCode` for this? Just store the images as `acat.jpg`, `bcat.jpg`, `ccat.jpg` and so on. – Bergi Feb 24 '16 at 15:36
  • `fromCharCode` is to convert a `unicode number` into a `character`, nothing to do with a character from user input. – Munawir Feb 24 '16 at 15:39
  • Please be more specific. What you actually need ? The character typed in the textbox ? – Munawir Feb 24 '16 at 15:41
  • Iv'e been asked to use fromcharcode from my lecturer, it's not my idea, as I don't really see how it is relevant. – seanrs97 Feb 24 '16 at 15:55
  • @Bergi - I understand what you're saying, but how would I actually go about displaying these images if the letter is typed in from the user? – seanrs97 Feb 24 '16 at 15:56
  • @Munawir - Yes, when the user types a character into the input box, so for e.g. they're typing in their name, so it could be John, I then need the appropriate images to be displayed onto the screen from this, so cat_j.jpg, cat_o.jpg, cat_h.jpg, cat_n.jpg. – seanrs97 Feb 24 '16 at 15:59
  • @seanrs97: Yes, exactly like that. Use the `oninput` event on the box, then get the value and manipulate the DOM to show the respective images. What part of that do you have a problem with exactly? Please try something and show us your code. – Bergi Feb 24 '16 at 16:06

1 Answers1

0

You need this

function myfun() {
  var text = document.getElementById("tb").value;
  for (var i = 0; i < text.length; i++) {
    var letter = text.charAt(i);
    var img = document.createElement("img");
    var att = document.createAttribute("src");
    att.value =  "cat_"+letter+".jpg";
    img.setAttributeNode(att);
    document.body.appendChild(img);
  }
}
<input type="text" id="tb">
<button onClick="myfun()">Get Image</button>
Munawir
  • 3,346
  • 9
  • 33
  • 51