javascript - How to replace an image on the page with another image by clicking on the image? -
i not javascript or html expert. know basic.
here code click on image open file chooser , choose new image , append previous image. works fine need replace image previous 1 instead of appending. appreciate if 1 can tweak i'm not sure how it:
<div id="current-user"></div> <br> <input type="file" id="choose" multiple src="/logo.png" /> <script> function readimage(file) { var reader = new filereader(); var image = new image(); reader.readasdataurl(file); reader.onload = function(_file) { image.src = _file.target.result; // url.createobjecturl(file); image.onload = function() { var w = this.width, h = this.height, t = file.type, // ext only: // file.type.split('/')[1], n = file.name, s = ~~(file.size/1024) +'kb'; $('#uploadpreview').append('<img src="'+ this.src +'"> '+w+'x'+h+' '+s+' '+t+' '+n+'<br>'); }; image.onerror= function() { alert('invalid file type: '+ file.type); }; }; } $("#choose").change(function (e) { if(this.disabled) return alert('file upload not supported!'); var f = this.files; if(f && f[0]) for(var i=0; i<f.length; i++) readimage( f[i] ); }); </script>
edit:
i handle page bring image , append previous image. need remove previous image , add new image. used method of replacewith() , replcaall() didn't work.
instead of:
$('#uploadpreview').append(...
use:
$('#uploadpreview').html(...
using html()
method replaces inner hmtl content #uploadpreview
element
Comments
Post a Comment