I would like to use the HTML5 File API with unobtrusive JavaScript. But I can only get it working by calling JavaScript functions from the HTML. Is there any way to use the File API with unobtrusive JavaScript?
The File API is not supported by all browsers, but I have tried this in Google Chrome and in Firefox.
From the documentation this works:
<input type="file" id="input" onchange="handleFiles(this.files)">
And I have tried with this unobtrusive JavaScript that doesn't work:
window.onload = function() {
var input2 = document.getElementById('input2');
input2.addEventListener('onchange', handleFiles);
}
A complete example is below, and testable on jsFiddle.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
var input2 = document.getElementById('input2');
input2.addEventListener('onchange', handleFiles);
}
function handleFiles(e) {
alert('got files');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input1" onchange="handleFiles(this.files)"/>
<input type="file" id="input2"/>
</body>
</html>
Try:
window.onload = function() {
var input2 = document.getElementById('input2');
input2.addEventListener('change', handleFiles,false);
// ^not onchange ^older firefox needs this
}
jsfiddle here
not onchange but
input2.addEventListener('change', handleFiles);
Related
I want to be able to open files through input type="file" in chrome apps.
The following code produce an error:
Refused to execute inline event handler because it violates the
following Content Security Policy directive
<html>
<head>
<title></title>
</head>
<body>
<input type="file" onchange="btnClick(event)" />
<script>
function btnClick(evt) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
var str = event.target.result;
console.log(str);
}
fileReader.readAsText(event.target.files[0]);
}
</script>
</body>
</html>
What can I do to fix it?
Inline event handlers dont work in chrome apps, remove event handler from the html and implement it in javascript. Also, the script must not be in the html file. it should be in its own js file and referenced in the html. This is documented HERE
html
<input type="file" id="file1"/>
js
document.getElementById("file1").addEventListener("change",handleChange);
function handleChange(){
var fileReader = new FileReader();
fileReader.onload = function (event) {
var str = event.target.result;
console.log(str);
}
fileReader.readAsText(event.target.files[0]);
}
FIDDLE
I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
whether there is an example of such an implementation?
howto load/save context of msxml to/from edit or text control?
<html><head>
<script language="JavaScript">
function loadxml()
{
var fileName = document.getElementById("fileName");
var xmlData = new ActiveXObject("Msxml2.DOMDocument");
xmlData.load(fileName.value);
var editor = document.getElementById("editor");
editor.value = xmlData; // got [object]
}
function testxml()
{
var editor = document.getElementById("editor");
// editor.value load by msxml
}
</script>
</head>
<body>
<input type="file" id="fileName"/>
<input type="button" value="Load" onclick="loadxml();"/>
<input type="button" value="Test" onclick="testxml();"/><br>
<textarea id="editor" rows="25" cols="50">no data</textarea>
</body>
</html>
editor.value = xmlData.xml
And vice-versa only use loadXML instead of load method on ActiveX object
var xmlData = new ActiveXObject("Msxml2.DOMDocument");
xmlData.loadXML( editor.value );
see for ex. http://joncom.be/code/javascript-xml-conversion/
PS Originally misunderstood question, so there are irrelevant comments now
How do I modify this mathjax example to live preview while I type? Right now it only displays result after I have pressed enter. I would like to tweak it so that it works similar to how stackoverflow/math.stackexchange shows the preview when typing a question.
<html>
<head>
<title>MathJax Dynamic Math Test Page</title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [["$","$"],["\\(","\\)"]]
}
});
</script>
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full">
</script>
</head>
<body>
<script>
//
// Use a closure to hide the local variables from the
// global namespace
//
(function () {
var QUEUE = MathJax.Hub.queue; // shorthand for the queue
var math = null; // the element jax for the math output.
//
// Get the element jax when MathJax has produced it.
//
QUEUE.Push(function () {
math = MathJax.Hub.getAllJax("MathOutput")[0];
});
//
// The onchange event handler that typesets the
// math entered by the user
//
window.UpdateMath = function (TeX) {
QUEUE.Push(["Text",math,"\\displaystyle{"+TeX+"}"]);
}
})();
</script>
Type some TeX code:
<input id="MathInput" size="50" onchange="UpdateMath(this.value)" />
<p>
<div id="MathOutput">
You typed: ${}$
</div>
</body>
</html>
Instead of using onchange try onkeypress or onkeyup.
onchange is only triggered when you leave the field, but the others (obviously) happen with each key-stroke.
I suspect you are using Internet Explorer, which doesn't fire onchange events as often or efficiently as other browsers.
The version in the MathJax Examples includes more code to handle IE better. You might want to look at the source code there for details.
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [ ['$','$'], ["\\(","\\)"] ],processEscapes: true}});
</script>
<script
type="text/javascript"
charset="utf-8"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
function f() {
var input = document.getElementById("input");
document.getElementById("output").innerHTML = input.value;
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
</script>
<textarea id="input" cols="25" rows="5" onkeyup="f()">
</textarea>
<p id="output"></p>
I'd like to have a page redirecting to another using Javascript. I've tried with document.location.href but it doesn't work with local pages (stored in my hard drive).
Does someone know something that would do the trick ?
thanks,
Bruno
Doesn't it? I've tried the following and it works fine:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<input type="text" value="" id="test"/>
</body>
<script type="text/javascript">
document.location.href = "file:///C:/dev/PICCS/vb/binaries/";
</script>
</html>
Tested in IE8 and Chrome
Posting this on the xul file of the extension :
function Read(file)
{
var ioService=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream=Components
.classes["#mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel=ioService.newChannel(file,null,null);
var input=channel.open();
scriptableStream.init(input);
var str=scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
}
gBrowser.addEventListener("DOMContentLoaded", function(e) {
var documentElement = e.originalTarget.defaultView.document;
var div = documentElement.createElement("div");
div.innerHTML = Read("chrome://firefox_extension/content/locale.html");
documentElement.body.appendChild(div);
},
false
);
the complete extension : http://uploadingit.com/file/xef7llflgmjgfzin/my_firefox_extension.xpi