how to remove c fakepath in webkit browser like chrome, safari, opera? - javascript

How to remove c fakepath in webkit browser like chrome, safari, opera ?
in IE And Firefox it's show only file name , it's OK
But in Chrome, opera, safari. It's show C:\fakepath\700.jpg
How can i remove C:\fakepath\ in Chrome, opera, safari.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js"></script>
<style type="text/css">
.inputWrapper {
overflow: hidden;
position: relative;
cursor: pointer;
/*Using a background color, but you can use a background image to represent a button*/
background-color: #DDF;
}
.fileInput {
cursor: pointer;
height: 100%;
position:absolute;
top: 0;
right: 0;
/*This makes the button huge so that it can be clicked on*/
font-size:50px;
}
.hidden {
/*Opacity settings for all browsers*/
opacity: 0;
-moz-opacity: 0;
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)
}
</style>
<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$(function() {
$(".inputWrapper").mousedown(function() {
var button = $(this);
button.addClass('clicked');
setTimeout(function(){
button.removeClass('clicked');
},50);
});
$('input[type=file]').change(function() {
var $this = $(this);
$this.parent().find('span').text($this.val());
});
});
});//]]>
</script>
<div class="inputWrapper" id="inputWrapper" style="height: 56px; width: 128px;">
<input class="fileInput hidden" type="file" name="file2"/>
<span></span>
</div>

Just use a regular expression to remove everything before (and including) the last \.
var path = "C:\\fakepath\\example.doc";
var filename = path.replace(/^.*\\/, "");
console.log(filename);
Obviously, you'd get path from your file input.

And you will get the name of first file.
document.getElementById("yourInputElement").files[0].name
If you want to get multiple filenames, you have to iterate over files.

Something like the following should work for you:
<script type="text/javascript">
$(function() {
$(".inputWrapper").mousedown(function() {
var button = $(this);
button.addClass('clicked');
setTimeout(function(){
button.removeClass('clicked');
},50);
});
$('input[type=file]').on('change', function(e) {
var filename = $(e.currentTarget).val().replace(/^.*\\/, "");
$this.parent().find('span').text(filename);
});
});
</script>

Use Below Code :
<label for="file" class="input input-file"><div class="button"><input type="file" onchange="this.parentNode.nextSibling.value = this.value" name="uploadfiliron" class="uploadimg" data-gotfile='uploadimg-1'>Browse</div><input type="text" readonly class="uploadimg-1"></label>
And This is script
<script>$('body').on('change','.uploadimg',function(e){
var filename = $(this).val().replace(/.*(\/|\\)/, '');
var getft = $(this).attr('data-gotfile');
console.log(getft+" "+filename);
if(filename=='')
{
$('.'+getft).val('No file chosen');
}
else
{
$('.'+getft).val('Your file name: '+filename);
}});</script>

Related

upload with multiple image preview

I am using this source: http://opoloo.github.io/jquery_upload_preview/
until now, I can upload one image with preview.
<style type="text/css">
.image-preview {
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
background-color: #000000;
color: #ecf0f1;
}
input[type="file"] {
line-height: 200px;
font-size: 200px;
position: absolute;
opacity: 0;
z-index: 10;
}
label {
position: absolute;
z-index: 5;
opacity: 0.7;
cursor: pointer;
background-color: #bdc3c7;
width: 200px;
height: 50px;
font-size: 20px;
line-height: 50px;
text-transform: uppercase;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("image-preview").each(
function(){
$.uploadPreview({
input_field: $(this).find(".image-upload"),
preview_box: this,
label_field: $(this).find(".image-label")
});
}
);
});
</script>
<!--| catatan penting: yang penting action="" & input type="file" name="image" |-->
<form action="upload.php" method="POST" enctype="multipart/form-data">
<div class="image-preview">
<label for="image-upload" class="image-label">+ GAMBAR</label>
<input type="file" name="my_field[]" class="image-upload" />
</div>
<div class="image-preview">
<label for="image-upload" class="image-label">+ GAMBAR</label>
<input type="file" name="my_field[]" class="image-upload" />
</div>
<input type="submit"/>
</form>
then try to add more div class image preview, i want add another button with image preview. i don't want multiple upload with one button.
$(document).ready(function() {$.uploadPreview => use id, of course when change to class and add more div, when upload a button, another button will change. i am confused with the logic. Anyone can help? maybe using array but, i don't know how..
Since upload button is dependent on state of uploadPreview you need to initialize for each div separately to get separate upload buttons.
Change your html like this give each container a class say imgBox
<div class="imgBox">
<label for="image-upload" class="image-label">Choose File</label>
<input type="file" name="image" class="image-upload" />
</div>
.....
....
...
<div class="imgBox">
<label for="image-upload" class="image-label">Choose File</label>
<input type="file" name="image" class="image-upload" />
</div>
..
Now initialize each one using jquery each()
$(".imgBox").each(
function(){
$.uploadPreview({
input_field: $(this).find(".image-upload"),
preview_box: this,
label_field: $(this).find(".image-label")
});
});
I created a simple image uploading index.html file for image uploading and preview.
Needs j-query.No need of extra plugins.
If you have any questions ask me ;)
//to preview image you need only these lines of code
var imageId=idOfClicked;
var output = document.getElementById(imageId);
output.src = URL.createObjectURL(event.target.files[0]);
Check it here:
https://jsfiddle.net/chs3s0jk/6/
I have one better option for the file upload it's easy to use and you can try it.
window.onload = function(){
if(window.File && window.FileList && window.FileReader){
$(document).on("change",'.file', function(event) {
var files = event.target.files; //FileList object
var output = document.getElementById("upload-preview");
$("#upload-preview").html("");
if(files.length>5){
$(".file").after("<div class='alert alert-error'><span class='close'></span>Maximum 5 files can be uploaded.</div>");
$(this).val("");
return false;
}
else{
$(".file").next(".alert").remove();
}
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
// if(!file.type.match('image'))
if(file.type.match('image.*')){
if(this.files[0].size < 2097152){
// continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.className = "upload-preview-thumb";
div.style.backgroundImage = 'url('+picFile.result+')';
output.insertBefore(div,null);
});
//Read the image
$('#clear, #upload-preview').show();
picReader.readAsDataURL(file);
}else{
alert("Image Size is too big. Minimum size is 1MB.");
$(this).val("");
}
}else{
alert("You can only upload image file.");
$(this).val("");
}
}
});
$(".file2").change(function(event){
var err=0;
var input = $(event.currentTarget);
var ele = $(this);
var file = input[0].files[0];
var u = URL.createObjectURL(this.files[0]);
var w = ele.attr("data-width");
var h = ele.attr("data-height");
var img = new Image;
img.onload = function(){
if(w){
if(img.width!=w || img.height!=h){
ele.parent().find(".alert").remove();
ele.parent().find(".upload-preview").before("<div class='alert alert-error'>Please upload a image with specified dimensions.</div>");
ele.val("");
}
else{
ele.parent().find(".alert").remove();
}
}
};
img.src = u;
var nh;
if($(this).attr('data-preview')=='full')
nh = (h/w*150)
else
nh=150
var preview = ele.parent().find(".upload-preview");
var reader = new FileReader();
preview.show();
reader.onload = function(e){
image_base64 = e.target.result;
preview.html("<div class='upload-preview-thumb' style='height:"+nh+"px;background-image:url("+image_base64+")'/><div>");
};
reader.readAsDataURL(file);
});
}
else
{
console.log("Your browser does not support File API");
}
}
above code save as one js file like file-upload.js
then link it to your file where you want perview.
i.e.
<script src="js/file-upload.js" type="text/javascript"></script>
use this kind of example for the input type
<input type="file" class="file2" name="page-image" id="page-image"/>
that works on the class that name is "file2" that class you given to the input field that able to create preview.
full structure something like below.
HTML Code you can try
<input type="file" class="file2" name="page-image[]" id="page-image"/>
<div class="clearfix"></div>
<div class="upload-preview" style="display: block;">
<div class="upload-preview-thumb">
// perview genereate here
// you can display image also here if uploaded throw the php condition in edit image part
</div>
</div>
<input type="file" class="file2" name="page-image[]" id="page-image"/>
<div class="clearfix"></div>
<div class="upload-preview" style="display: block;">
<div class="upload-preview-thumb">
// perview genereate here
// you can display image also here if uploaded throw the php condition in edit image part
</div>
</div>
CSS
.upload-preview {
border: 1px dashed #ccc;
display: block;
float: left;
margin-top: 10px;
padding: 5px;
}
.upload-preview-thumb {
background-position: 50% 25%;
background-size: cover;
float: left;
margin: 5px;
position: relative;
width: 139px;
}
Hope this works and in future it's helpful for you.
Thanks.

how to hide loading image after load chart in d3?

$(document).on('click', '.tbtn', function(e) {
$('#loading-image').show();
if(error){
$('loading-image').hide();
else{
val = $('.barbtn input:checked').val();
draw_summary($.parseJSON(data['summary']),val);
draw_barchart($.parseJSON(data['barchart']),val);
draw_scatter($.parseJSON(data['table']),val);
$('#loading-image').show();
}
});
Here i have drawing charts using d3...charts are coming correctly but i need to set loading image when i onclick the button...this code is not working
how to set loading image when onclick the button?
You just need to set CSS for it. Otherwise you are following right path. Please check below snippet.
$(document).on('click', '.tbtn-hide', function(e) {
$('#loading-image').hide(); //hide loader
});
$(document).on('click', '.tbtn-show', function(e) {
$('#loading-image').show(); //show loader
});
#loading-image
{
background: white url("http://smallenvelop.com/demo/simple-pre-loader/images/loader-64x/Preloader_1.gif") no-repeat scroll center center;;
height: 80%;
left: 0;
position: fixed;
top: 10;
width: 100%;
z-index: 9999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="tbtn-hide">Hide</button>
<button class="tbtn-show">show</button>
<div id="loading-image" style="display:none">
</div>
$(document).on('click', '.tbtn', function(e) {
$('#loading-image').show();
$.ajax({
success:function(result){
val = $('.barbtn input:checked').val();
draw_summary($.parseJSON(data['summary']),val);
draw_barchart($.parseJSON(data['barchart']),val);
draw_scatter($.parseJSON(data['table']),val);
$('#loading-image').hide();
}
});
});

Textarea counter / countdown with negative numbers and enforcement

I've been working on adding a character counter to a TEXTAREA field. There are many, many solutions available online for this task.
"Stop-at-Zero" Solution
The problem I'm having is that practically all solutions terminate user input at 0. That's effective, I guess, but it's not optimal in terms of user-friendliness. For example, if a user pastes text into the TEXTAREA, and the text exceeds the field's limitation, this stop-at-zero solution will abruptly truncate the excess text. The user then has to work to find the missing content and then edit their message, submit a second form, or some other burden.
"Negative Character Count" Solution
Other solutions allow the user to enter all they want. The character counter will go from positive to negative. The problem with these counters is lack of enforcement: They allow users to submit the form even with a negative character count.
Twitter Solution
I think Twitter has it right. They let users input all they want and highlight the excess text with a negative character count (and a colored background, which I don't need to have). They disable the submit button while the count is negative.
My (Incomplete) Solution
Working with third-party code I found through Google, I've devised a character counter that works perfectly in terms of the count. But being somewhat new to JS I haven't been able to code the enforcement part.
Here's my question:
How do I get the code to prevent submission of the form when the counter is a negative number?
HTML
<form action="" method="post">
<div>
<textarea name="comments" id="comments" cols="50" rows="10"></textarea>
</div>
<div>
<input type="submit">
</div>
</form>
CSS
form div {
position: relative;
}
form .counter {
position: absolute;
left: 300px;
bottom: -25px;
font-size: 25px;
font-weight: bold;
color: #ccc;
}
form .warning {color: orange;}
form .exceeded {color: red;}
JavaScript
<script src="/js/jquery.js"></script>
<script>
(function($) {
$.fn.charCount = function(options){
// default configuration properties
var defaults = {
allowed: 100,
warning: 25,
css: 'counter',
counterElement: 'span',
cssWarning: 'warning',
cssExceeded: 'exceeded',
counterText: ''
};
var options = $.extend(defaults, options);
function calculate(obj){
var count = $(obj).val().length;
var available = options.allowed - count;
if(available <= options.warning && available >= 0){
$(obj).next().addClass(options.cssWarning);
} else {
$(obj).next().removeClass(options.cssWarning);
}
if(available < 0){
$(obj).next().addClass(options.cssExceeded);
} else {
$(obj).next().removeClass(options.cssExceeded);
}
$(obj).next().html(options.counterText + available);
};
this.each(function() {
$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
calculate(this);
$(this).keyup(function(){calculate(this)});
$(this).change(function(){calculate(this)});
});
};
})(jQuery);
</script>
<script>
$(document).ready(function(){
$("#comments").charCount();
});
</script>
https://jsfiddle.net/nyc212/sk5kfopw/
I have modified your plugin to take the submit button as first parameter.
If you want it to be more dynamic:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
form div {
position: relative;
}
form .counter {
position: absolute;
left: 300px;
bottom: -25px;
font-size: 25px;
font-weight: bold;
color: #ccc;
}
form .warning {
color: orange;
}
form .exceeded {
color: red;
}
</style>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
(function($) {
$.fn.charCount = function(btnsub, options){
this.btnsub = btnsub;
// default configuration properties
var defaults = {
allowed: 100,
warning: 25,
css: 'counter',
counterElement: 'span',
cssWarning: 'warning',
cssExceeded: 'exceeded',
counterText: ''
};
var options = $.extend(defaults, options);
function calculate(obj,btnsub){
btnsub.attr("disabled", "disabled");
var count = $(obj).val().length;
var available = options.allowed - count;
if(available <= options.warning && available >= 0){
$(obj).next().addClass(options.cssWarning);
} else {
$(obj).next().removeClass(options.cssWarning);
}
if(available < 0){
$(obj).next().addClass(options.cssExceeded);
} else {
$(obj).next().removeClass(options.cssExceeded);
btnsub.removeAttr("disabled");
}
$(obj).next().html(options.counterText + available);
};
this.each(function() {
$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
calculate(this, btnsub);
$(this).keyup(function(){calculate(this,btnsub)});
$(this).change(function(){calculate(this,btnsub)});
});
};
})(jQuery);
$(document).ready(function(){
$("#comments").charCount($("#btnsub"));
});
</script>
</head>
<body>
<form method="post">
<div>
<textarea name="comments" id="comments" cols="50" rows="10"></textarea>
</div>
<div>
<input type="submit" id="btnsub">
</div>
</form>
</body>
</html>
I would try either by disabling the submit button using the disabled attribute, or preventing the form from submitting using e.preventDefault. I updated your fiddle...just uncomment either of the options
https://jsfiddle.net/sk5kfopw/1/

Using JavaScript to change text on the page every half-second

So, what I'm hoping to do is change the text inside a set of <p> tags every half-second. The set of tags in question is in this block of code in my body:
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
Right below the above code I have the JavaScript that should call a function every half-second:
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
I have the function changeMatrixText defined inside my head:
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
As you see, that's supposed to set the text to a random string of 0's and 1's. But it's not working. Any idea why?
Just in case you need to see my entire code .....
<html>
<head>
<title>Simple encrypt/decrypt</title>
<style type="text/css">
body
{
background-color: #A9F5F2;
width: 900px;
padding: 0px;
}
.outerdiv
{
margin: 5px;
border: 2px solid #FF8000;
background-color: #FFFFFF;
}
.outerdiv > p
{
margin: 5px;
word-wrap:break-word
}
.outerdiv > h1
{
margin: 5px;
}
#col1
{
width: 500x;
height: 800px;
float: left;
}
#col2
{
width: 295px;
height: 1500px;
float: right;
font-family: Courier New;
overflow: hidden;
}
#title1div
{
font-family: Arial;
width: 100%;
}
#insctdiv
{
font-family: Arial;
width: 100%;
}
#iptdiv
{
height: 400px;
width: 100%;
}
#buttonsdiv
{
text-align: center;
width: 100%;
}
#inputText
{
width: 100%;
height: 100%;
resize: none;
}
</style>
<script type="text/javascript">
function encrypt()
{
var text = document.getElementById("inputText").value;
newstring = "";
/* Make newstring a string of the bit representations of
the ASCII values of its thisCharacters in order.
*/
for (var i = 0, j = text.length; i < j; i++)
{
bits = text.charCodeAt(i).toString(2);
newstring += new Array(8-bits.length+1).join('0') + bits;
}
/* Compress newstring by taking each substring of 3, 4, ..., 9
consecutive 1's or 0's and it by the number of such consecutive
thisCharacters followed by the thisCharacter.
EXAMPLES:
"10101000010111" --> "10101401031"
"001100011111111111111" --> "0011319151"
*/
newstring = newstring.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});
document.getElementById("inputText").value = newstring;
}
function decrypt()
{
var text = document.getElementById("inputText").value;
text = text.trim();
text.replace(/([2-9])([01])/g,
function (all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
}).split(/(.{8})/g).reduce(function (str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
document.getElementById("inputText").value = text;
}
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
</script>
</head>
<body>
<div id="col1">
<div class="outerdiv" id="title1div">
<h1>Reversible text encryption algorithm</h1>
</div>
<div class="outerdiv" id="insctdiv">
<p>Type in or paste text below, then click <b>Encrypt</b> or <b>Decrypt</b></p>
</div>
<div class="outerdiv" id="iptdiv">
<textarea id="inputText" scrolling="yes"></textarea>
</div>
<div class="outerdiv" id="buttonsdiv">
<button onclick="encrypt()"><b>Encrypt</b></button>
<button onclick="decrypt()"><b>Decrypt</b></button>
</div>
</div>
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
</body>
</html>
In essence, I'm trying to make the right column of my page keep printing inside a new string of 0's and 1's every half-second, kinda like on the computer screen on the movie The Matrix, if you catch my drift.
According to MDN, the elements with a value attribute include <button>, <option>, <input>, <li>, <meter>, <progress>, and <param>. You'll need to set the innerHTML instead.
document.getElementById("matrixText").value = newtext;
to
document.getElementById("matrixText").innerHTML = newtext;
and
setInterval("changeMatrixText()", 500);
to
setInterval(changeMatrixText, 500);
Working Demo
document.getElementById("matrixText").value = newtext;
.value is used for form fields instead use
document.getElementById("matrixText").innerHTML = newtext;
in your changeMatrixText function
Here's an example of how you can do this:
http://jsfiddle.net/35W4Z/
The main difference is that a <p> element doesn't have a .value attribute. Instead, use the innerHTML attribute (as shown in the JSFiddle example)
Hope this helps!
Well for fun, I stuck this in a fiddle: http://jsfiddle.net/jdmA5/1/
So two things, mostly:
1) You can't set the "value" of a div element. You have to set the .innerHTML:
document.getElementById("matrixText").innerHTML = newtext;
2) This could be due to the fact I built this out in fiddle, but setInterval is notorious for not running like you expect unless you give each iteration its own memory space. I did this by wrapping the call to changeMatrix in a anonymous function:
setInterval(function() {changeMatrixText();}, 500);
Check out the jsfiddle link to see it in action.
Have you tried changing the setInterval method to accept the first argument as the function itself (the name, minus the parentheses), rather than a string...
As you are not passing any parameters explicitly, you can invoke the function as follows:
setInterval(changeMatrixText, 500);
Should you have needed to supply some parameters, then the following would work:
setInterval(function() {
changeMatrixText(myParam1, myParam2); // etc, etc
}, 500);

Onclick switch from one to two images then back to one

Trying to figure out how to switch from one to two images then back to one with an onlick.
So far I have below which works no problem for switching to one image and back to original image. Ultimately I'm trying to get the first onclick event to be two images vertically and then click again back to the first single image.
var play = false;
function toggle() {
var image = document.getElementById('image')
var scan = document.getElementById('scan');
play = !play;
if (play) {
image.src = "pause.png";image.width="182";image.height="182";image.border="0";
scan.play();
}
else {
image.src = "play.png";image.width="182";image.height="182";image.border="0";
scan.pause();
}
}
and in body:
<img onclick="toggle()" id="image" src="play.png" alt="image" width="182" height="182" style="margin:auto; position:absolute; top: 0; right: 0; bottom: 0; left: 0; border: 0;">
This should work fine except, take out the width, height and border from the javascript, they're not changing so why have it there and risk some browsers freaking out on them?
I just put this together real quick to test and it works a treat.. I've commented out scan.play and pause of course but I'm assuming you've checked the console in your browser to see if those are throwing any errors?
I took the <a> out and used style cursor=pointer instead for the click-able element as well.. either way works but this is neater and works from ie6 I think, ie7+ definately.
edit: removed source block didn't achieve goal of question
After discussion in comment there's heaps of ways to do it, and I'd probably use jQuery but since you're not here's one not
<!doctype html>
<html>
<head>
<script type="text/javascript">
var play = true;
function toggle() {
//var scan = document.getElementById('scan');
var playpause = document.getElementById('playpause');
var btnplay = playpause.getElementsByClassName('play');
var btnpause = playpause.getElementsByClassName('pause');
play = !play;
if (play) {
btnplay[0].className = 'btn play active';
btnpause[0].className = 'btn pause';
//scan.play();
}
else {
btnplay[0].className = 'btn play';
btnpause[0].className = 'btn pause active';
//scan.pause();
}
}
</script>
<style>
.btn {
width: 182px;
height: 182px;
cursor: pointer;
position: absolute;
visibility: hidden;
}
.btn.active { visibility: visible; }
.btn.play { background: url('play.png') no-repeat 0 0; }
.btn.pause {
background: url('pause.png') no-repeat 0 0;
padding: 182px 0 0 0;
}
</style>
</head>
<body>
<div id="playpause">
<div class="btn play active" onclick="toggle()">
</div>
<div class="btn pause" onclick="toggle()">
<img src="other.png" alt="other" />
</div>
</body>
</html>

Categories