How to make a button display the value of a file/image? Javascript

I have a button called f1 and I want it to display the value of the image that the user puts when they select an image. For example, when you select an image it'll display on the screen but I also want it to display on the button with proper width and height attributes, how would I do that? I've tried the document.getElementById("f1").innerHTML = input.value; but that only displays the file path, not the actual image. I appreciate the help.

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img')
                    .attr('src', e.target.result)
                    .width(250)
                    .height(200);
					
				
            };
			reader.readAsDataURL(input.files[0]);
			const f1 = document.getElementById("f1").innerHTML = input.value;

            
			
        }
    }
#f1 {
		width:50px;
		height:40px;
	}
	#img {
		position:relative;
		left:275px;
		top:200px;
	}
<!DOCTYPE html>
<html>
<head>
	<title>Filter Image</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  </head>

<body>
 <input type='file' id="file" onchange="readURL(this);" accept="image/gif, image/jpeg, image/png">
    <img id="img"/>
	<button id = "f1"></button>
</body>
</html>

1 answer

  • answered 2019-09-21 17:49 abhishek.s

    function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
    
                reader.onload = function (e) {
                    $('#img')
                        .attr('src', e.target.result)
                        .width(50)
                        .height(50);
    					
    				
                };
    			reader.readAsDataURL(input.files[0]);
    			 }
        }
    <!DOCTYPE html>
    <html>
    <head>
    	<title>Filter Image</title>
    	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      </head>
    
    <body>
     <input type='file' id="file" onchange="readURL(this);" accept="image/gif, image/jpeg, image/png">
        
    	<button id = "f1"><img id="img"/></button>
    </body>
    </html>