Search code examples
javascriptsrcinputbox

Get img src from input box into a div


The idea behind this small project of mine is to have an user enter an URL for an img, when the user hits a button the img should then be inserted into a new <div> within the page.

I tried looking for hours at stackoverflow but I honestly don't understand how I can use other answers to my own code. Most of the CSS and HTML code is already done, I just need help with the javascript part if its possible at all.

Here is what I have so far:

HTML code:

<form name="imgForm">
  enter URL:
  <input type="text" name="inputbox1" value="src" />
  <input type="button" value="Get Feed" onclick="GetFeed()" />
</form>

Javascript code:

<script type="text/javascript">
  function GetFeed(imgForm) {
    var imgSrc = document.getElementById("src").value;
  }
</script>

Can anyone help me out? I dont know where to go from here.. at least give me some pointers how can i get the value from the txt box and add a new <div><img src="user input from txt box should go here"/></div> for every time an unser inserts and new URL for an img?


Solution

  • I think according to your need how can i get the value from the txt box and add a new <div><img src="user input from txt box should go here"/></div> you need this

    HTML

    <form>
      <input type="text" id="txt">
      <input id="btn" type="button" value="Get Image" onclick="getImg();" />
    </form>
    <div id="images"></div>
    

    JS (goes inside your head tags)

    function getImg(){
        var url=document.getElementById('txt').value;
        var div=document.createElement('div');
        var img=document.createElement('img');
        img.src=url;
        div.appendChild(img);
        document.getElementById('images').appendChild(div);
        return false;
    }
    

    Here is an example. ​