Forum Moderators: open
This works in IE but not netscape
Trying to let users change a image on a page with javascript
If I hard code img path like
document.imgname.src = "blah.gif"; //it works fine but
But this doesn't work in netscape but does in IE
document.picture.src = document.pictureform.imgfile.value;//where imgfile is vale from text box of type="file"
Seems if dynamically changing an image using value from a text box it doesn't work
Think it's a string oblect thing but don't know how to fix it
Here is the code I use
<head>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
if(document.images) {
function showImage() {
if(document.images){
document.picture.src = document.pictureform.imgfile.value;
alert(document.pictureform.imgfile.value);
}
}
}
window.onerror = null;
//-->
</script> </head>
<body>
<form method="post" action="" name="pictureform">
<br />
<input type="file" name="imgfile"><a href="javascript:showImage();">Show Image</a>
</FORM>
<img name="picture" src=""/>
</body>
Any tips would be great
You should be able to copy code into editor and use as is, for testing
Thanks
Trent
I have made a couple of other changes too.
- Reference image via document.images collection
- Removed outer IF block. The whole idea is too avoid an error if the document.images collection is not supported (v.v. unlikely these days). With the IF block an error will occur because the function won't be defined, yet it will still be called.
<script language="javascript" type="text/javascript">
function showImage()
{
if(document.images){
document.images.picture.src = "file:///"+document.pictureform.imgfile.value;
}
}
</script>
<form>
<strong>Browse for Photo:</strong>
<input type="file" name="photo" onChange="previewImage(this.form,this.value);">
<input type="submit" name="submitButton" value="Upload">
</form>
<img name="preview" id="preview" src="spacer.gif" width="200" alt="" border="0">
function previewImage(form,path) {
if (path!= '') {
document.preview.src=path;
}
}
Notice I've only spec'd "width="200" in the preview object. Raw camera images are several thousand pixels wide, and this limits the preview to 200 px wide and the height scales proportionately, so it doesn't blow up the page.
For some reason though, I can't get it to work in FireFox. :-) FireFox responds to the onChange, just doesn't populate the image object.
document.preview.src= "file:///"+path;
notes:
1) It seems to work with only 2 slashes in file://
2) This leads to paths like:
file:///C:\myimages\animage.jpg
It also works if you flip the slashes:
document.preview.src= "file:///"+path.replace(/\\/g,"/");
=> file:///C:/myimages/animage.jpg
3) It all fails in Opera. It seems that the input value only returns the image name, not the full path.