0

What I did already is as user writes some text, script adds it to UTL and loads a picture under the text input box.

What I want to do more is to be able to split input text by space (ex. A1369 A2453 should be sliced into two variables A1369 and A2453) and use these two variables to load all the pictures below input box.

The string length has to be unlimited.

I have read and tried to understand javascript split function, but had no success using it yet.

Code that I have now below:

<script type="text/javascript">
    document.getElementById('btn').onclick = function() {
        var val = document.getElementById('imagename').value,
            src = 'http://s7ondemand6.scene7.com/is/image/MothercareASE/l' + val.toLowerCase() +'_1?&$dw_large_mc$&wid=1059&hei=1272',
            img = document.createElement('img');

        img.src = src;
parentElement.insertBefore(img, parentElement.firstChild);
    }
</script>

How do I add the splicing using the String.prototype.split function?

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Possible duplicate of http://stackoverflow.com/questions/14912502/how-do-i-split-a-string-by-whitespace-and-ignoring-leading-and-trailing-whitespa and http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript – Oceans Jan 28 '16 at 14:33

1 Answers1

0

The core of the problem is simple. You have to use val.split(" ") which creates array of strings. You can then do a loop and create image for every sub-string:

var values = val.split(" ");
for(var i=0, l=values.length; i<l; i++) {
   var url = 'http://s7ondemand6.scene7.com/is/image/MothercareASE/l' + values[i].toLowerCase() +'_1?&$dw_large_mc$&wid=1059&hei=1272';
   ... javascript to show image belongs here ...
}

I created full code example. I used functions to separate code in smaller chunks. I strongly advise you to do that too.

Full code:

document.getElementById('btn').onclick = function() {
  var val = document.getElementById('imagename').value;
  document.getElementById('imagename').value = "";
  // turn "XXX XXX" into ["XXX", "XXX]
  var vals = val.split(" ");

  for(var i=0,l=vals.length; i<l; i++) {
    var img = document.createElement('img');
    img.src = createImageUrl(vals[i]);
    addImage(img);
  }

}
/**
  This function adds image to the beginning of image list **/
function addImage(imageElm) {
  var container = document.getElementById("images");
  if(container.firstChild) {
    container.insertBefore(imageElm, container.firstChild);
  }
  else {
    container.appendChild(imageElm);
  }
}
/**
  This function generates correct image URL **/
function createImageUrl(ID) {
  return 'http://s7ondemand6.scene7.com/is/image/MothercareASE/l' + ID.toLowerCase() +'_1?&$dw_large_mc$&wid=1059&hei=1272';
}
img {
  margin: 3px;
  max-width: 300px;
}
<input type="text" id="imagename" /><button id="btn">
Click to show.
</button>
<div id="images">

</div>
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778