I wish to change the file upload value when the file name (uploaded file) is too long. For example, if the file name is "This_file_has_a_long_name.txt", I wish to display it with limited characters like "This_file..name.txt".
So I tried the following but it is not working. Please advise.
$("#file_browser").change(function()
{
var filename = this.value;
filename = filename.substr(0,10);
alert(filename);
document.getElementById("file_browse").value = filename;
});
you cant change a property name in js cause of security normaly you will have
a msg SecurityError: The operation is insecure.
if you want you do that you need its to hide the default input file css go to google for that you have tuto
and add your filname custom in a <p></p> for exemple and place where you want
if you really need to change name do that on server side
good day
Try this :
Note:if length of name be 14 and greater , change it.
$(document).ready(function() {
$("#file_browser").change(function() {
var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
//Or for full path use, var filename = $(this).val();
var len = filename.length;
if (len <= 13 ) {
$("#file_browse").text(filename);
}
else {
var part1 = filename.substr(0,5);
var part2 = filename.substr(len - 8);
$("#file_browse").text(part1 + "..." + part2);
}
})
})
<input type="file" id="file_browser">
<p id="file_browse"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
What about some trick.
JS
$("#file_browse").change(function()
{
var data = $(this).val();
$(this).val();
data = data.replace(/(.{1,10}).{1,}(.{6})/,"$1..$2");
$("#file_browse").after("<div style='position:absolute; top:4px; margin-left:230px;'>"+data+"</div>");
});
The add the following css
input[type=file]
{
color:transparent;
}
Adjust the margin-left and top position.
Store the filename into the variable data.
Then make an empty field by using $(this).val(); So your input type file label contain like No file choose are some thing like, this is because of to avoid your input file name is so long means scroll will appear.
Use the pattern replace for include dots.
Then make the div tag for write the filename.
Don't forgot to add the css for transparent file text color.
You better use the name property to get just the file name and hide the default file input because you can't change its value.
$("#fileInput").change(function () {
if (this.files.length === 0) {
return;
}
var name = this.files[0].name;
if (name.length > 14) {
name = name.substr(0, 7) + "..." + name.substr(-7);
}
$("#fileNameText").text(name);
});
$("#chooseButton").click(function () {
$("#fileInput").click();
});
<form>
<input type="file" id="fileInput" style="display: none" />
<button type="button" id="chooseButton">Choose file</button>
<span id="fileNameText">Select a file</span>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I am using this code to show a preview of an image URL.
<input name="input_19" id="input_2_19" type="text" value="" class="medium" placeholder="http://" aria-invalid="false">
<script>
jQuery('#input_2_19').blur(function() {
var src = jQuery(this).val();
var previews = jQuery(".previewImage");
var drawPreview = true;
var PreviousSource = jQuery(this).data('previousSource');
if(!src.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$") && src != "")
{
jQuery("#warning").html("Must be an image");
return false;
} else {
jQuery("#warning").html("");
}
jQuery.each(previews , function(index, value) {
if (src == "" && PreviousSource == $(value).attr('src'))
{
jQuery(value).remove();
drawPreview = false;
return false;
}
if( jQuery(value).attr('src') == src)
{
drawPreview = false;
return false;
}
});
if(drawPreview) {
jQuery('#prev').append('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
}
var previousSource = jQuery(this).data('previousSource', src);
});
</script>
<div id="warning"></div>
<div id="prev"></div>
It works well, but if I change the image URL then the second image will show up too and the first will stay.
How do I make it so only one image preview is shown?
https://jsfiddle.net/LucyTech/qohxryL4/4/
Also why doesn't it work with some images eg
https://ae01.alicdn.com/kf/HTB1q0ucSYrpK1RjSZTEq6AWAVXap/Mifa-Portable-Bluetooth-speaker-Portable-Wireless-Loudspeaker-Sound-System-10W-stereo-Music-surround-Waterproof-Outdoor-Speaker.jpg
what is wrong with this url? In the browser it shows an image so why does the code give an error?
Please use this javascript. That will give you result as per your expectation.
$('#input_2_19').blur(function() {
console.log(jQuery(this).val());
var src = jQuery(this).val();
var previews = $(".previewImage");
var drawPreview = true;
var PreviousSource = $(this).data('previousSource');
if(src.match("/\.(jpeg|jpg|gif|png)$/") != null && src != "")
{
$("#warning").html("Must be an image");
return false;
} else {
$("#warning").html("");
$('#prev').html('<img class="previewImage" style="max-width:50px;" src="' + src + '">');
}
});
Using append() will always add a new element. Maybe you should include the img tag in the initial html with its own id property and change its src property with attr(). You can use show() and hide() on an image element or you can wrap it in a div/span and hide this one.
Before appending the
below code should work.
jQuery('#prev').html('');
After this add your img tag
jQuery('#prev').html('<img class="previewImage" style="max-width:500px;" src="' + src + '">');
The problem of the image not previewing for some the links I think is related to the regular expression that you wrote in the str.math I am not very good in so I can not help you with it but I took a look at your post's first comment "Jinesh", his/her regular expression seems to work. For the other problem, I wrote some piece of code for with comments to fix the the multiple image
// When you release the keyboard key
$("#urlInput").keyup(function(){
$("#warning").text(""); // Clear message div
var url = $("#urlInput").val(); // get url in the input box
if(isValidImageUrl(url)) // Validate the url
$("#prevImg").attr("src", url).show(); // Change src of th eimg tag and Show it
else
$("#prevImg").attr("src", "").hide(); // If the url is not valid, hide the img tag in the html
});
// When you get out the side the input box such as clicking outside or pressing tab key
$("#urlInput").blur(function(){
var url = $("#urlInput").val(); // Get the url in the input box
if(!isValidImageUrl(url)) // Validate the url
$("#warning").text("Must be an image"); // if the url is invalid show warning
});
// Valdiate url fucntion
function isValidImageUrl(checkUrl){
return checkUrl.match("^https?://(?:[a-z\-]+\.)+[a-z]{2,10000}(?:/[^/#?]+)+\.(?:jpg|gif|png|jpeg)$");
}
img{
width: 100px;
height: 100px;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="warning"></div>
<input id="urlInput">
<div id="prev">
<img id="prevImg">
</div>
I'm trying to get the number of files selected and change a div based on the number. The code I have is this:
HTML:
<input type="file" name="submit_image[]" id="submit_image" class="fileStyle" multiple>
Javascript:
//Get Files
var files = document.getElementById("submit_image");
function listFiles() {
var numFiles = files.length;
alert(numFiles);
}
//Test button to give me number of files
document.getElementById("test").onclick = function (e) {
listFiles();
}
When I click the button it just returns undefined. I would be open to doing this in jQuery but I prefer a Vanilla JS method. Thanks for the help.
You forgot to access the files property of the input element:
var files = document.getElementById("submit_image").files;
Fixed by this code:
var list = document.getElementById("submit_image");
function listFiles () {
var numFiles = list.files.length;
alert(numFiles);
}
document.getElementById("test").onclick = function (e) {
listFiles();
}
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
But in this task, firstly I try to catch that input in javascript file, and I am failing in the same. Can you tell me for this, which command will I use ?
Till now my work is :-
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT FILE:-
function addString(x) {
var val = x.name.value;
//var s = document.getElementById("name_id").getElementValue;//x.name.value;
alert(val);
}
EDITED
My New JAVASCRIPT FILE IS :-
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the string, but unable to show on the web page.
See this fiddle: http://jsfiddle.net/MjyRt/
Javascript was almost right
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
alert(s);
}
Try to use jQuery (simpler)
function addString() {
var s = $('#name_id').val();//value of input;
$('#list').append(s+"<br/>");//list with entries
}
<div id='list'>
</div>
I'm trying to make a game in javascript. I still have many issues in the code. The code is supposed to have 2 buttons; one for shuffling images dice and a button to check if the kid wrote the correct answer or not.
2 buttons
1 textbox
and a place to show the answer if it's correct or not
Here is my code.
I don't know why when I put the source of document.getElementbyID("test") it shows nothing
because I want every time I click on start a random image is selected.
I would appreciate any help as I am still a beginner in javascript.
<head>
<script type="text/javascript">
function startf(){
var images = [];
index = 0;
images[0] = "<img src='1.png' length=70px width=75px>";
images[1] = "<img src='2.png' length=70px width=75px>";
images[2] = "<img src='3.png' length=70px width=75px>";
images[3] = "<img src='4.png' length=70px width=75px>";
index = Math.floor(Math.random() * images.length);
take(index);
function take(ind)
{
return document.getElementbyId("ind")="What should i put here";
}
}
function check(){
var ch=getElementbyId("answer").value;
if (ch=index+1)
{
document.getElementbyId.innerHTML="TRUE";
}
else
{
document.getElementbyId.innerHTML="False";
}
}
</script><br>
</head>
<img id="test" src="" alt="..." length="75px" width="75px" />
<body>
<input type="button" value="start" onclick="startf()">
<input id="answer" type="text" name="checkvalue" value="Enter Value" onclick="check()">
<div id="fa">
</div>
<input type="button" value=chek onclick="check()">
</body>
1- Put and end to each instructions --> ;
2- Do not use document.getElementById directly, there will be at least one occurence with an error into it and you don't want that.
function _e(id) {
return document.getElementById(id);
}
3- Always put brackets and (...) around your IF-ELSE blocks:
if (...) {
//....
} else {
//....
}
4- Every tag attributes should have " " around their values, for example:
<input type="button" value="start" onclick="check()" />
5- You could only put image paths in your array since it seems to be what needs to be updated in #test image.
It is document.getElementById check the casing. Your check function is wrong... you can't assign a value to document.getElementById function. Also your if is wrong. Do you know any JavaScript?
I'm guessing what you want is probably something like this. You seem to be trying to add or replace an element just by using document.getElementById(id) = something but that's not how it works. Instead, to change an image to another file you need to alter its src attribute. (There are other ways but this is maybe the simplest.)
// Declare the variable called number here so it can be accessed
// by all of the following functions.
var number;
// a simple function to save typing document.getElementById all the time
function _e(id) {
return document.getElementById(id);
}
function startf() {
// Pick a number between 1 and 4
number = Math.floor(Math.random() * 4 + 1);
// Set the image with id 'test' to have the source 1.png, 2.png etc.
_e('test').src = number + '.png';
}
function check() {
// note that == is used for comparison, = is used for assignment
if (_e('answer').value == number) {
_e('fa').innerHTML = "TRUE";
}
else {
_e('fa').innerHTML = "False";
}
}
How to get type of file that user has selected (in some <input type="file" name="datafile">) with jQuery and for example alert it? At least its extention but some kind of grouped types like image would be grate. Is there any jQuery plugin for that?
$('input[type=file]').change(function(e){
var file = $(this).val();
var ext = file.split('.').pop();
alert(ext);
});
Try this :)
Just provide an id to you input and use this
document.getElementById(ID).files[0].type
Try this to get your file extension.
var fileName = "Ram.png";
alert(fileName.substring(fileName.lastIndexOf('.') + 1));
why don't you use something like this:
$('input:file').change(function () {
var ext = this.value.split('.').pop();
console.log(ext);
});
if you want to use a "multiple" field, you can use something like this:
$('input:file').change(function () {
var $this = $(this);
if ( $this.prop('multiple') ) {
for ( var i=0; i<this.files.length; i++) {
var ext = this.files[i].fileName.split('.').pop();
// this.files[i].extension = ext; // usefull for future use
console.log(ext);
}
}
else {
console.log(this.value.split('.').pop());
}
});