Replace text to image in jquery - javascript

This is my jquery script for validating the file extension.
function ValidateExtension() {
var allowedFiles = [".csv", ".xlsx", ".txt"];
var fileUpload = document.getElementById("product_file1");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "Your file has been imported.Please wait few for minutes";
return true;
}
Here! what I am trying to do, The above code is like this:
lblError.innerHTML = "Your file has been imported.Please wait few for minutes";
But I am changing link this,
lblError.innerHTML = '<img src="/assets/spin.gif">';
NOTE:Why? I am editing this code means.When i have to uploading a file the message will be display the text but i want display image only,
This is possible?

Always remember you need to use escape characters while you try to insert an image tag in innerHTML component. Do it like this and it will 100% work .Try this code below
<img src=\`assets/spin.gif\`>
Let me know if that helps :)

Yes, is possible.
Look https://jsfiddle.net/1kzoqg8x/
var lblError = document.getElementById("lblError");
lblError.innerHTML = '<img src="http://media.iterar.co/app-site/images/spinner.gif" />';
This is it you need?

Related

Issue with Unicode characters in photoshop javascript code

I have created a JSX for reading the data from TAB delimited input file (input file has two columns; ID and description). I want to read the input file and place the description on text layer and save the filename with ID.
It works when the description field letters and numbers. But it does not work when it has (é) in the description.
var Description = "on the ***pavé***";
textlayer.textItem.encoding = "UTF-8";
textlayer.textItem.contents = Description;
textlayer.textItem.tracking =50;
textlayer.textItem.wrapBend=70;
var saveFile = new File(outputfolder + "\\" + ID + "_16.psd");
saveFile.encoding="UTF-8";
app.activeDocument.saveAs( saveFile, saveOptions, true );
Works for me:
// Switch off any dialog boxes
displayDialogs = DialogModes.NO; // OFF
var outputfolder = "C:\\temp";
var description = "pavé_16";
var mySaveFile = outputfolder + "\\" + description + ".psd";
var psdFile = new File(mySaveFile);
activeDocument.saveAs(psdFile, SaveDocumentType.PHOTOSHOP, true, Extension.LOWERCASE);
displayDialogs = DialogModes.ALL; // NORMAL
Are you sure you're saving out as pavé_16.psd and not ***pavé***_16.psd? As asterisks (stars) in your filename will not work :)

Javascript : how inject a variable with html content to a data-attribute appended?

I wish to insert a variable that contains an HTML code in a DATA attribute (a href ... data-content= ...) it not work very well because the code inserted deletes some characters and suddenly it does not display properly.
Here is the code used
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('<i class="fa fa-file-o"></i> Aperçu');
}
AND my HTML output return this :
"><i class="fa fa-file-o"></i> Aperçu
Why it doesn't work ? What should I do?
Thank You
The problem with your code is there is special characters in the preview value . If you use code given below then you can override the problem and this is not the proper way and avoid this kind of coding style.Use data attributes for integers,small string values etc.. contents like html or long string values etc either use public properties or hidden controls.
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('</i> Aperçu');
$(".preview").data("content",preview);
}
well, lets fix this for the first: you have double quotes in the preview var you should escape them with '\' e.g.:
var preview = '<img src=\"' + url + '\" width=\"250\">';
or better use single quotes inside the var
var preview = "<img src='" + url + "' width='250'>";
but I think it's not good approach to store html in this attr - would be better to store here url only and html in the separate template. or render the hidden element on page load

How to add custom image tag to pagedown?

I'm attempting to duplicate the original img tag's functionality in custom img tag that will be added to the pagedown converter.
e.g I'm copy the original behavior:
![image_url][1] [1]: http://lolink.com gives <img src="http://lolink.com">
into a custom one:
?[image_url][1] [1]: http://lolink.com gives <img class="lol" src="http://lolink.com">
Looking at the docs the only way to do this is through using the preblockgamut hook and then adding another "block level structure." I attempted doing this and got an Uncaught Error: Recursive call to converter.makeHtml
here's the code of me messing around with it:
converter.hooks.chain("preBlockGamut", function (text, dosomething) {
return text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, function (whole, inner) {
return "<img src=" + dosomething(inner) + ">";
});
});
I'm not very experienced with hooks and everything so what would I do to fix it? Thanks.
UPDATE: found out that _DoImages runs after prespangamut, will use that instead of preblockgamut
Figured it out! The solution is very clunky and involves editing the source code because I am very bad at regex and the _DoImage() function uses a lot of internal functions only in the source.
solution:
All edits will be made to the markdown.converter file.
do a ctrl+f for the _DoImage function, you will find that it is named in two places, one in the RunSpanGamut and one defining the function. The solution is simple, copy over the DoImage function and related stuff to a new one in order to mimic the original function and edit it to taste.
next to DoImage function add:
function _DoPotatoImages(text) {
text = text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writePotatoImageTag);
text = text.replace(/(\?\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writePotatoImageTag);
return text;
}
function writePotatoImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
var whole_match = m1;
var alt_text = m2;
var link_id = m3.toLowerCase();
var url = m4;
var title = m7;
if (!title) title = "";
if (url == "") {
if (link_id == "") {
link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
}
url = "#" + link_id;
if (g_urls.get(link_id) != undefined) {
url = g_urls.get(link_id);
if (g_titles.get(link_id) != undefined) {
title = g_titles.get(link_id);
}
}
else {
return whole_match;
}
}
alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()");
url = escapeCharacters(url, "*_");
var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
title = attributeEncode(title);
title = escapeCharacters(title, "*_");
result += " title=\"" + title + "\"";
result += " class=\"p\" />";
return result;
}
if you look at the difference between the new _DoPotatoImages() function and the original _DoImages(), you will notice I edited the regex to have an escaped question mark \? instead of the normal exclamation mark !
Also notice how the writePotatoImageTag calls g_urls and g_titles which are some of the internal functions that are called.
After that, add your text = _DoPotatoImages(text); to runSpanGamut function (MAKE SURE YOU ADD IT BEFORE THE text = _DoAnchors(text); LINE BECAUSE THAT FUNCTION WILL OVERRIDE IMAGE TAGS) and now you should be able to write ?[image desc](url) along with ![image desc](url)
done.
The full line (not only the regex) in Markdown.Converter.js goes like this:
text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
so check the function writeImageTag. There you can see how the regex matching text is replaced with a full img tag.
You can change the almost-last line before its return from
result += " />";
to
result += ' class="lol" />';
Thanks for the edit to the main post.
I see what you mean now.
It is a bit weird how it uses empty capture groups to specify tags, but if it works, it works.
It looks like you would need to add on an extra () onto the regex string, then specify m8 as a new extra variable to be passed into the function, and then specify it as class = m8; like the other variables at the top of the function.
Then where it says var result =, instead of class =\"p\" you would just put class + title=\"" + .......

Import .CSV data into Javascript and run execute if string contains data

I have a couple of iMacro-files, that is executed with a single javascript file.
Very basic, looks like this.
iimPlay("GoogleMacro.iim");
iimPlay("IBMMacro.iim");
iimPlay("IMDBMacro.iim");
iimPlay("AltavistaMacro.iim");
iimPlay("GametrailersMacro.iim");
iimPlay("MortalCombatMacro.iim");
iimPlay("WikipediaMacro.iim");
It is called playme.js, and works really good.
Though, I don't want to run every macro each time I launch the .js file.
I have a separate CSV-file, urldata.csv
URLINFO,URLINFO2,DATA1,DATA2
http://google.com,GOOGLE,"hello","thank you for searching"
http://ibm.com,IBM,null,null
http://imdb.com,IMDB,null,null
http://altavista.com,ALTAVISTA,"rip","rest in peace, my friend",
http://gametrailers.com,GAMETRAILERS,null,null
http://mortalkombat.wikia.com,MORTALKOMBAT,null,null
http://wikipedia.org,WIKIPEDIA,null,null
The way I want it to work, in this case (the data above in urldata.csv), the .js file would only execute GoogleMacro.iim and AltavistaMacro.iim
The rule I am looking for: If COL3 has the value null, do not iimPlay, and check the next file in line.
The .JS code should work (I am very aware of this is just gibberish) like this:
#Import urldata.csv
Loop whole CSV {
ROW2, If COL3 = null --> go to ROW3
else iimPlay("GoogleMacro.iim");
ROW3, If COL3 = null --> go to ROW4
else iimPlay("IBMMacro.iim");
Etc..
}
I need to figure out:
How to import/read the data from urldata.csv to my playme.js. Apparently, jQuery is not allowed in the free version of iMacros and therefore I cannot use this.
How to make a function that only use iiPlay if the value on row X is something else than null.
Please help! :)
Solved!
Changed the .csv to the following:
"http://google.com",GoogleMacro,"hello","thank you for searching"
"http://ibm.com",IBMMacro,"",""
"http://imdb.com",IMDBMacro,"",""
"http://altavista.com,ALTAVISTAMacro","rip","rest in peace, my friend",
"http://gametrailers.com",GAMETRAILERSMacro,"",""
"http://mortalkombat.wikia.com",MORTALKOMBATMacro,"",""
"http://wikipedia.org",WIKIPEDIAMacro,"",""
And got some really good help with the .js
var load;
load = "CODE:";
load += "SET !DATASOURCE urldata.csv" + "\n";
load += "SET !DATASOURCE_COLUMNS 4" + "\n";
load += "SET !DATASOURCE_LINE {{i}}" + "\n";
load += "SET !extract {{!col2}}" + "\n";
load += "ADD !extract {{!col3}}" + "\n";
var siteName = "";
var siteContent = "";
//Change 4 to the number of websites
for(i=1;i<4;i++) {
iimSet("i",i);
// Load data
iimPlay(load);
siteName = iimGetLastExtract(1);
// Check if the website has content
siteContent = iimGetLastExtract(2);
if(siteName != "Website" && siteContent != "") {
iimPlay(siteName + '.iim');
} else {
}
}
Make a GET request to get the contents of your CSV file (jQuery might help with that), then use a CSV parser (maybe https://stackoverflow.com/a/14991797/711902) to parse the file, then loop through each row, and call the function if it matches your expectation.
jQuery.get('urldata.csv', function(response) {
var data = parseCSV(response);
for (var i = 1; i < data.length; i++) {
var col3 = data[2], url = data[0];
if (col3 != 'null') {
var site = getSiteFromUrl(url);
iimPlay(site + 'Macro.iim');
}
}
});
function getSiteFromUrl(url) {
var site = url.match(/\/\/(.*)\./)[1];
return site[0].toUpperCase() + site.substr(1);
}

Use jQuery to get the file input's selected filename without the path

I used this:
$('input[type=file]').val()
to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.
How can I just get the file name (filename.doc)?
var filename = $('input[type=file]').val().split('\\').pop();
or you could just do (because it's always C:\fakepath that is added for security reasons):
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):
var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()...
var file = path.split('\\').pop();
jsFiddle.
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
jsFiddle.
...or lastIndexOf()...
var file = path.substr(path.lastIndexOf('\\') + 1);
jsFiddle.
Here is how I do it, it works pretty well.
In your HTML do:
<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
Then in your js file create a simple function:
function fileSelect(id, e){
console.log(e.target.files[0].name);
}
If you're doing multiple files, you should also be able to get the list by looping over this:
e.target.files[0].name
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
How about something like this?
var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers
var fileUpload = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0);
var files = fileUpload.files;
var mediafilename = "";
for (var i = 0; i < files.length; i++) {
mediafilename = files[i].name;
}
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Categories