I have a form with 2 types of image input(from file and from URL). I need to use image from the last changed input. For this I made an additional invisible input field "imgTempURL" , which fills with image's url(or base64 string, if it's a file) when one of the input fields is changed.
For example, if I upload a file to the file input,"imgTempURL" value changes to base64 string. If I fill the URL field value, "imgTempURL" value changes to the URL field value. Then I press a button and "imgTempURL" value is sent to the server. That how it works.
The problem is that "imgTempURL" isn't filled with new base64 string, if I try to upload a file after I filled URL input field - it remains with the same old url link value.
Here's the part of HTML:
<input type="text" id="imgTempUrl"/> <--made it visible to see its value-->
<cfform id="form">
Use file
<input type="file" id="imgUp" accept=".jpg">
or URL
<input type="text" name="url" id="url" size="20"
onkeyup="document.getElementById('imgTempUrl').value=this.value;">
<input type="Submit" class="" value="Generate" id="generate">
</cfform>
I get base64 string with in this function:
$(function(){
$('#imgUp').change(function(){
imgUp = document.getElementById('imgUp');
if(imgUp.files && imgUp.files[0]){
var reader = new FileReader();
reader.onload = function(e){
$('#imgTempUrl')
.attr('value', e.target.result);
};
reader.readAsDataURL(imgUp.files[0]);
}
});
});
How can I solve this problem? Is there something I should know about working with file inputs and their behavior?
Thank you in advance!
$('#imgTempUrl').attr('value',e.target.result);
This is not the way to set value of an input text. You should use .val()
method to set the value.
$(function(){ $('#imgUp').change(function(){ imgUp = document.getElementById('imgUp'); if(imgUp.files && imgUp.files[0]){ var reader = new FileReader(); reader.onload = function(e){ $('#imgTempUrl').val(e.target.result); }; reader.readAsDataURL(imgUp.files[0]); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="imgTempUrl"/> <--made it visible to see its value--><br> <cfform id="form"> Use file <input type="file" id="imgUp" accept=".jpg"> <br> or URL <input type="text" name="url" id="url" size="20" onkeyup="document.getElementById('imgTempUrl').value=this.value;"> <input type="Submit" class="" value="Generate" id="generate"> </cfform>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.