Passing argument from html to JavaScript function and displaying results in html

In this post, we will demonstrate following things with a very simple html , JavaScript code,

  • Get input from user ( In this example, image url)
  • On Clicking Button, pass this url as argument to JavaScript function
  • Set this argument to element to be used again in html
<!DOCTYPE html>
      Enter Image URL: <input type="text" name="img_url" id="img_url">
      <button onclick="displayImage(document.getElementById('img_url').value)">Display Image</button>
      <img id="imagedisplay"></img>
         function displayImage(url) {
           var x = document.getElementById("imagedisplay");
           x.src = url;

In above example, we are getting the input url from user in argument “img_url” declared using “id” , then we try to access this argument’s value using getElementById as “document.getElementById(‘img_url’).value”. This value is then passed to javascript function “displayImage”

This function, access’s the html element by Id defined for displaying image using “img” tag, and assign that argument received from html to “src” of img element.

Leave a Comment