How to access files attribute of a file element using JavaScript - javascript

I have in my form an input element with type of file. What I like to do is to check the file size before the element is uploaded for validation issue. By using the majority of primary Web Browsers (except IE that always does things harder), I have find out that all are using an "attribute" that updated whenever I choose a new file and display the file size, as well other usefull information.
Here is what I see in Chrome web browser :
The question now is, how can I access that value with JavaScript ? I have try several ways, but none was good for me ? Any good idea please ?
NOTE: In my web site I use jQuery, so is not important to be only regular JavaScript the answer.
Kind regards
Merianos Nikos

//use any ol' selector to get the <input /> element:
var inputElement = document.querySelector("input[type='file']");
//then it's just like you'd access any object's attributes:
var fileSize = inputElement.files[0].size;
//note that it's a list of files, so you can loop through them
//in case the element accepts multiple files
//if you want all of the attributes, do something like:
for (var key in inputElement.files[0])
if (inputElement.files[0].hasOwnProperty(key))
console.log(key,inputElement.files[0][key]);

or :
$("#btStartUpload").on("click", function(evt) {
var filesSelected = document.getElementById('btInput').files; // FileList object
// var filesSelected = $('#btInput')[0].files; // with jQuery, any jQuery object have it's DOM element accessed using [0]
// var filesSelected = $('input[type=file]')[0].files;
console.log(filesSelected);
});

Related

Get elements inside several html documents

I have a functionality in my system that transcripts from voice to text using an external library.
This is what the library renders:
What I need is really simple: to get the text from the generated textareas.
The textareas are rendered without any name or id, so I can only access them by class in the Google Chrome console. Whenever I try to get them by class in my javascript code, I get an array of [0] elements.
I think that the problem is that this library renders a new #document and I'm not able to get it's content in my $(document).ready function because it scopes the 'parent' document.
How it renders.
Any thoughts on this? Thank you.
I hope the code below helps.
// Get you iframe by Id or other way
let iframe = document.getElementById("myFrame");
// After iframe has been loaded
iframe.onload= function() {
// Get the element inside your iframe
// There are a lot of ways to do it
// It is good practice to store DOM objects in variables that start with $
let $elementByTag = iframe.contentWindow.document.getElementsByTagName("p")[0];
let $elementById = iframe.contentWindow.document.getElementById("elementId");
let $elementByClass = iframe.contentWindow.document.getElementsByClassName("classHere");
let $elementBySelector = iframe.contentWindow.document.querySelector("#dad .classname");
// After get the element extract the text/html
let text = $element.innerText
let html = $element.innerHTML
};

How to access the TYPO3 settings in JavaScript

In my project we're using TYPO3. We're getting some data from the backend and they're assigned as follows in the html page itself.
var items = {};
items.item1 = {settings.item1};
items.item2 = {settings.item2};
items.item3 = {settings.item3};
and then the values are being assigned to the buttons. Those values will be sent back to the JS when an action has triggered. The {settings.item*} comes from the TYPO3 backend. What I wanted to know is how can I add the above code block in a separate JS file rather than adding it in the HTML page. When I tried adding it directly, it doesn't work as the {settings.item*} comes from TYPO3
Thanks
You have to pick up your settings from the HTML since this is what TYPO3 will render for you. but you could rather make use of the data-attributes of HTML, e.g.
You could also render the whole {settings} array as a JSON string into a data-attribute and pick that up with your JavaScript.
You can use javascript on html file (templates , partial , layouts )
You need to add javascript code between the
Syntax:
<![CDATA[ javascript code ]]> TYPO3 Code <![CDATA[ javascript code ]]>
<script type="text/javascript">
<![CDATA[
{
var items = {};
items.item1 = ]]>{settings.item1}<![CDATA[;
items.item2 = ]]>{settings.item2}<![CDATA[;
items.item3 = ]]>{settings.item3}<![CDATA[;
]]>
</script>
Thanks
I hope it helps !!
Can you define the context more precisely? Where are the settings defined, inside of TypoScript, Flexform, PHP (Extensionmanager)?
If you have settings defined in TypoScript you can use:
page.inlineSettings {
setting1 = Hello
setting2 = GoOnTop
}
To make them available in JavaScript as:
TYPO3.settings = {"TS":{"setting1":"Hello","setting2":"GoOnTop"}};
See: https://docs.typo3.org/typo3cms/TyposcriptReference/Setup/Page/Index.html#inlinesettings
Perhaps this will be removed in future versions as it's purpose is usage via ExtJS. Also it's not possible to use stdWrap and such.
Another, more flexible, way is using
page.jsInline {
10 = TEXT
10.stdWrap.dataWrap = var pageId = {TSFE:id};
}
This allows you to use full TypoScript like TEXT, dataWrap, etc.
See: https://docs.typo3.org/typo3cms/TyposcriptReference/Setup/Page/Index.html#jsinline
I wouldn't write JavaScript from PHP just for some configuration. I would store them in data-attributes of a DOM element and grab it via JavaScript. Maybe this is also an option for you.

How to pass arguments to external Javascript files? [duplicate]

I read the tutorial DIY widgets - How to embed your site on another site for XSS Widgets by Dr. Nic.
I'm looking for a way to pass parameters to the script tag. For example, to make the following work:
<script src="http://path/to/widget.js?param_a=1&param_b=3"></script>
Is there a way to do this?
Two interesting links:
How to embed Javascript widget that depends on jQuery into an unknown environment (Stackoverflow discussion)
An article on passing parameters to a script tag
I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.
<script src=".." one="1" two="2"></script>
Inside above script:
document.currentScript.getAttribute('one'); // 1
document.currentScript.getAttribute('two'); // 2
Much easier than jQuery or URL parsing.
You might need the polyfill for document.currentScript from #Yared Rodriguez's answer for IE:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
It's better to Use feature in html5 5 data Attributes
<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>
Inside the script file http://path.to/widget.js you can get the paremeters in that way:
<script>
function getSyncScriptParams() {
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript;
return {
width : scriptName.getAttribute('data-width'),
height : scriptName.getAttribute('data-height')
};
}
</script>
Got it. Kind of a hack, but it works pretty nice:
var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];
I pass the params in the script tag as classes:
<script src="http://path.to/widget.js" class="2 5 4"></script>
This article helped a lot.
Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:
<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />
The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):
var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;
Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...
JQuery has a way to pass parameters from HTML to javascript:
Put this in the myhtml.html file:
<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>
In the same directory make a subscript.js file and put this in there:
//Use jquery to look up the tag with the id of 'myscript' above. Get
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");
//print filename out to screen.
document.write(filename);
Analyze Result:
Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.
jsfiddle proof that the above works:
http://jsfiddle.net/xqr77dLt/
Create an attribute that contains a list of the parameters, like so:
<script src="http://path/to/widget.js" data-params="1, 3"></script>
Then, in your JavaScript, get the parameters as an array:
var script = document.currentScript ||
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();
var params = (script.getAttribute('data-params') || '').split(/, */);
params[0]; // -> 1
params[1]; // -> 3
If you are using jquery you might want to consider their data method.
I have used something similar to what you are trying in your response but like this:
<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>
You could also create a function that lets you grab the GET params directly (this is what I frequently use):
function $_GET(q,s) {
s = s || window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
// Grab the GET param
var param_a = $_GET('param_a');
Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.
HTML:
<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
<button id='clickButton'>Click me</button>
</div>
JavaScript:
$(document).ready(function() {
var fetchData = $("#dataDiv").data('arg1') +
$("#dataDiv").data('arg2') ;
$('#clickButton').click(function() {
console.log(fetchData);
})
});
Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0
On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.
Source: https://api.jquery.com/data/
it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.
Basically I used the document.currentScript to get the element from where my code is running and I filter using the name of the variable I am looking for. I did it extending currentScript with a method called "get", so we will be able to fetch the value inside that script by using:
document.currentScript.get('get_variable_name');
In this way we can use standard URI to retrieve the variables without adding special attributes.
This is the final code
document.currentScript.get = function(variable) {
if(variable=(new RegExp('[?&]'+encodeURIComponent(variable)+'=([^&]*)')).exec(this.src))
return decodeURIComponent(variable[1]);
};
I was forgetting about IE :) It could not be that easier... Well I did not mention that document.currentScript is a HTML5 property. It has not been included for different versions of IE (I tested until IE11, and it was not there yet). For IE compatibility, I added this portion to the code:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
What we are doing here is to define some alternative code for IE, which returns the current script object, which is required in the solution to extract parameters from the src property. This is not the perfect solution for IE since there are some limitations; If the script is loaded asynchronously. Newer browsers should include ".currentScript" property.
I hope it helps.
This is the Solution for jQuery 3.4
<script src="./js/util.js" data-m="myParam"></script>
$(document).ready(function () {
var m = $('script[data-m][data-m!=null]').attr('data-m');
})
Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.
It's simpler if you pass arguments without names, just like function calls.
In HTML:
<script src="abc.js" data-args="a,b"></script>
Then, in JavaScript:
const args=document.currentScript.dataset.args.split(',');
Now args contains the array ['a','b']. This assumes synchronous script calling.
I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScript or the data attributes method would be most stylish.
This is the only of these methods not brought up here yet. Particularly, if for some reason you have great amounts of data, then the best option might be:
localStorage
/* On the original page, you add an inline JS Script.
* If you only have one datum you don't need JSON:
* localStorage.setItem('datum', 'Information here.');
* But for many parameters, JSON makes things easier: */
var data = {'data1': 'I got a lot of data.',
'data2': 'More of my data.',
'data3': 'Even more data.'};
localStorage.setItem('data', JSON.stringify(data));
/* External target JS Script, where your data is needed: */
var data = JSON.parse(localStorage.getItem('data'));
console.log(data['data1']);
localStorage has full modern browser support, and surprisingly good support of older browsers too, back to IE 8, Firefox 3,5 and Safari 4 [eleven years back] among others.
If you don't have a lot of data, but still want extensive browser support, maybe the best option is:
Meta tags [by Robidu]
/* HTML: */
<meta name="yourData" content="Your data is here" />
/* JS: */
var data1 = document.getElementsByName('yourData')[0].content;
The flaw of this, is that the correct place to put meta tags [up until HTML 4] is in the head tag, and you might not want this data up there. To avoid that, or putting meta tags in body, you could use a:
Hidden paragraph
/* HTML: */
<p hidden id="yourData">Your data is here</p>
/* JS: */
var yourData = document.getElementById('yourData').innerHTML;
For even more browser support, you could use a CSS class instead of the hidden attribute:
/* CSS: */
.hidden {
display: none;
}
/* HTML: */
<p class="hidden" id="yourData">Your data is here</p>

Saving without dialog window

I'm trying to write a script that will automate a bunch of stuff for Photoshop CS5. Part of this involves saving a bunch of files. Is there a way to save a file in a way that doesn't open up a dialog window? I've been looking over the JavaScript Tools Guide, but I didn't see a way to do this. This suggested I used an action to deal with it but I'd really prefer not to do that.
EDIT: specifically I want to save the files as crytiff format but I'd just like to know how to save a file with whatever extension I want
The following saves the active document as PNG. You can change the type to save it as.
// reference open doc
var doc = app.activeDocument;
// set save options
var opts = new ExportOptionsSaveForWeb();
opts.PNG8 = false;
opts.transparency = true;
opts.interlaced = false;
opts.quality = 100;
opts.includeProfile = false;
opts.format = SaveDocumentType.PNG; // Document Type
// save png file in same folder as open doc
activeDocument.exportDocument(doc.path, ExportType.SAVEFORWEB, opts);
Try using Document.saveAs(). But, like El Cas said, you still have to pass in some kind of SaveOptions object. You don't necessarily have to specify all the options if you don't want. You can just use the generic object like this:
app.activeDocument.saveAs(new File(doc.path + "/myDocument"), TiffSaveOptions);
// or BMPSaveOptions or GIFSaveOptions or JPEGSaveOptions...
Here's a much more complete Photoshop CS5 Javascript Reference
Open:
Windows > Actions
You will find Toggle Dialog On/Off check box before every action. Turn it off.

How to programmatically determine name of CKEditor instance

I've added a CKEditor instance programmatically to my page in the code-behind of my ASP.NET page:
VB.NET:
itemEditor = New CkEditor
cell.Controls.Add(itemEditor)
... which works fine. I can get the HTML on the postback and do stuff with it.
However, I also want to do some client-side stuff with it, specifically take a selected item out of another control, and insert it into the text by handling the onchange event.
So, how can I get the name of the editor instance in the JavaScript, so that I can do stuff like:
function GetCkText()
{
var htmlFromEditor = CKEDITOR.instances['editorName'].getData();
// do stuff with htmlFromEditor
}
Assuming you only have one editor instance:
for ( var i in CKEDITOR.instances ){
var currentInstance = i;
break;
}
var oEditor = CKEDITOR.instances[currentInstance];
Here is what the JavaScript API says about instances.
Here is another way of defining the CKEditor. Here 'fck' is the input fields id:
CKEDITOR.replace( 'fck', {
customConfig : prefix + 'js/ckeditor/config.js',
height: 600,
width: 950
});
editor = CKEDITOR.instances.fck;
Notice how I am then able to reference the instance using .fck.
If you only have a single instance and you do not know the name of it.
CKEDITOR.instances[Object.keys(CKEDITOR.instances)[0]].getData()
The following code:
var allInstances=CKEDITOR.instances;
for ( var i in allInstances ){
alert(allInstances[i].name);
}
works fine for me.
Well I've found a way... but I don't like it much...
I've added a Hidden Field control to the page, after adding the editor, and put the editor's ClientId in its value:
Dim hdn As New HiddenField
With hdn
.ID = "HiddenField"
.Value = itemEditor.ClientID
End With
cell.Controls.Add(hdn)
.. and then in the JavaScript, I can get the hidden field, and hence the editor name as follows:
function GetCkText()
{
var hdn = document.getElementById("HiddenField");
var editorName = hdn.getAttribute("value");
var editor = CKEDITOR.instances[editorName];
alert(editor.getData());
return false;
}
But it's a bit inelegant, to say the least. Anyone got a better way?
If you are using CKEDITOR.appendTo(...), keep in mind that the ckeditor does create an instance name internally. So you can query for that name immediately after creating it, then store it somewhere, and use it later.
var lvo_editor = CKEDITOR.appendTo( "my_div" , null , lvs_html ) ;
my_global_var = lvo_editor.name ;
by the way: The CKEDITOR.replace(...) method allows you to define an instance name (see answer above)
If you need the instance from a plugin, at least in version 4+ you can do this.
CKEDITOR.currentInstance
Here I am wanting to know the name of the textarea I applied ckeditor on.
CKEDITOR.currentInstance.name

Categories

Resources