Get img src from input box into a div

纵然是瞬间 提交于 2019-12-06 08:29:17

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. ​

You should add an id attribute to your <input>:

<input type="text" name="inputbox1" id="box1" value="src" /> 

...then, adjust your code:

var imgSrc = document.getElementById('box1').value; 

Once you have the source, you can get back an object for the img tag, and set its properties using the value from the text box. The img object's properties are defined by the Document Object Model:

http://www.w3schools.com/jsref/dom_obj_image.asp

Something like this will create a div with an image element that has a src equal to the text in the input box. It then appends the div to end of the page.

<html>
    <head>
        <script type="text/javascript">
            function GetFeed(form){
            var imgSrc = form.elements["inputbox1"].value;  
            var imgDiv = document.createElement('div');
            imgDiv.innerHTML = "<img src=\"" + imgSrc + "\"/>"
            document.body.appendChild(imgDiv);
            }
        </script>
    </head>
    <body>
        <form name="imgForm">
            enter URL:
            <input type="text" name="inputbox1" value="src" />  
            <input type="button" value="Get Feed" onclick="GetFeed(this.form)"/>
        </form>
    </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!