Update html with js instead of creating new file - javascript

at this moment my script downloads html file with name(1), name(2) etc. I wonder if I can change this script to update local file and add value instead of downloading. Or second option can I somehow force html to look for file "INCFINDERdb("highestvalue").html" ?
function save() {
var htmlContent = [document.getElementById('saveinc').value];
var bl = new Blob(htmlContent, {
type: "text/html"
});
var a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = "INCFINDERdb.html";
a.hidden = true;
document.body.appendChild(a);
a.innerHTML = " random ";
a.click();
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('click-me3').addEventListener('click', save);
});
<input type="text" id="saveinc">
<button class="button" id='click-me3'> Save INCs to ignore </button>
<div class="info-box">
IGNORUJEMY TE CI
<iframe src="/INCdb/INCFINDERdb.html" title="description"></iframe>
</div>
Later on I want to add remove option also with update does document.removeElement will work?

chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {
suggest({ filename: '..', conflictAction: 'overwrite' });
});
Fixed my problem

Related

Display image from a given url

I have an array with 3 cells.At the first cell i have a textarea where you can insert the url of an image.At the second cell i have a button which when you click the image display at the third cell where i have a div to display the image.The question is how can i display the image either from the internet either from local?
The code i wrote is:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
mydiv.innerHTML = url.value;
}
<html>
<body>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
img = document.createElement('img');
img.src = document.getElementById('imagename').value;
document.body.appendChild(img);
}
</script>
</body>
</html>
You can see the sample code will add the images from an array to the document.
You could also append the images to any of the elements in your function by using url.appendChild
var arr = ['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x250','http://via.placeholder.com/350x350']; // hold image urls in an array.
arr.forEach(function(item){
// loop through array and add images to the document.
var img = new Image();
img.src = item;
document.body.appendChild(img);
});
In order to do both you would need to change your html and code.
For the case when the user has a url you can just create a new image and append it to your div setting the image's src to the url that was set in the input:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
var image = new Image;
mydiv.appendChild(image);
image.src = url.value;
}
Now to get it to display a local image you will need a file input or a drag and drop scheme as you cannot access local files without some type of user interaction.
So you would, for example, need to change your html to include a file input, and grab a reference to the selected file the user selects. Then use FileReader to read the file, and finally display it
HTML
<input type="file" id="imagefile">
JS
//input reference
var imageinput = document.getElementById("imagefile");
imageinput.addEventListener('change',function (){
var mydiv = document.getElementById("idofdivtodisplayimg");
var image = new Image;
mydiv.appendChild(image);
//FileReader instance
var reader = new FileReader;
reader.addEventListener('load',function(){
//reader.result will contain a dataURL that can be used
//like a regular image url
image.src = reader.result;
});
//read the file as a dataURL
reader.readAsDataURL( imageinput.files[0] );
});
This does both, it let's you upload an image (or at least load it to the browser) or give a URL to an image source. Click the button and the image is loaded and displayed!
This snippet uses the FileReader API to get the uploaded image and display it in an image element
function uploadOrNot() {
if (document.querySelector("input[type=file]").files[0]){
let input = document.querySelector("input[type=file]");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
display(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
} else if (document.querySelector("input[type=text]").value){
display(document.querySelector("input[type=text]").value);
}
}
function display(res) {
let img = document.createElement("IMG");
img.src=res;
document.querySelector("#result").appendChild(img);
}
<div id="urlOrUpload">
<input type="text"/>
<br>
<input type="file" accetp="image/*"/>
</div>
<div id="buttonHolder">
<button type="button" onclick="uploadOrNot()">Display</button>
</div>
<div id="result"></div>
I partly solved it by replacing the div at the third cell with an img tag and at the function i wrote above, i chenged it to:
var image = document.getElementbyId("imageid");
var url = document.getElementbyId("urlid");
image.src = url.value;
But at the table i have,i also have a button where you can add a same row as above.How can i do this function for every url that is placed at every textbox?

Modifying URL with javascript

I have some simple code that allows you to enter Amazon isbns/asins and converts them to hyperlinks. These hyperlinks are Amazon.com searches for the said isbn/asin.
Example pic: http://imgur.com/a/rYgYt
Instead of the hyperlink being a search I would like the link to go directly to the products offer page.
The desired link would be as follows:
https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used
"ASIN" would be where the ASIN/ISBN would need to be populated to generate the link, for example:
Im asking if someone could help modify my existing code to create the change. My skills lack the ability to implement the change. The existing code is as follows:
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>
<script>
var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
var urls = []
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
urls=[];
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
urls.push(base + item);//add the url to our array of urls for button click
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
function openAllUrls(){
for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
window.open(urls[i]);
}
}
handler(); // run on load
</script>
</html>
to modify output URL, replace
var base = ".....';
with
var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';
and replace
base + item
with
basePrefix + item + baseSuffix

Is there a way to "onload" open a TXT file in textarea and automatically save it on close or URL change?

Is there a way to "onload" open a TXT file in textarea and automatically save it on close or URL change?
I need this to auto open a TXT file and auto save it when exiting the page or when closing the browser.
JavaScript:
/** ReLoad File BEGINS**/
function ReLoadFile()
{
var FileToLoad = document.getElementById("FileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("text").value = textFromFileLoaded;
};
fileReader.readAsText(FileToLoad, "UTF-8");
}
/** ReLoad File ENDS**/
/** Save File As FUNC p-1 BEGINS **/
var types = [
{"extension": ".html", "name": "HTML"},
{"extension": ".txt", "name": "Plain Text"},
{"extension": ".js", "name": "Javascript"},
{"extension": ".css", "name": "CSS"},
]
types.forEach(function(type) {
$opt = $("<option>").attr("value", type.extension).text(type.name)
$("#saveas").append($opt)
})
/** Save return if empty BEGINS**/
function SaveAsType()
{
if (document.getElementById("FileNameToSaveAs").value == "") {
alert("``Filename Save As`` name is empty.\n Please give the file a name that you will save it as, before you save it.");
return false;
} else {
/** Save File As FUNC p-2 BEGINS **/
{
console.log($("#saveas").val())
{
var textToSave = document.getElementById("text").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain" });
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("FileNameToSaveAs").value + "" + $("#saveas").val();
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
}
/** Save File As FUNC p-2 ENDS **/
}
}
/** Save return if empty ENDS**/
/** Save File As FUNC p-1 ENDS **/
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
/** Save File As ENDS **/
HTML:
<input type="file" id="FileToLoad" name="fileLoadName">
<input type="button" onclick="ReLoadFile();" value=" Re-Load ">
<textarea name="text" id="text" rows="34" cols="134" wrap="soft" placeholder="STEP - 1 : Put or load your web page Source Codes here"></textarea>
<textarea id="FileNameToSaveAs" rows="1" cols="30" maxlength="40" placeholder=" Filename Save As "></textarea>
<input type="button" onClick="SaveAsType();" value=" Save ">
using jquery you can do the auto open very easily:
$(document).ready(function() {
// do what you want with the text file
});
For dealing with when the browser closes you might be able to make use of jquery's unload() event. See here for documentation: https://api.jquery.com/unload/
Note that the unload event gets triggered when the user moves away from the page. Therefore, the back and forward buttons, as well as clicking on a link will trigger this event in addition to it being triggered when the browser is closed.

How to prevent uploaded image from getting deleted when editing a form?

I'm working on an app that allows users to post events. I'm using NodeJS, Express and Mongo.
I created a form that allows users to input event details, and upload an image relating to the event. I also created a form that allows the user to edit event details.
The form looks as follows:
The Problem:
User fills form with event details and attaches a picture.
User submits form
User decides he wants to change the event title, but NOTHING ELSE
User clicks edit event, changes the title, and submits
The problem: Even though the user didn't delete the picture associated with the event, the picture is no longer there.
Here is part of my new.ejs file (for posting new event, just adding this here for reference)
<script type="text/javascript" src="/js/eventform.js"></script>
<form action="/events"
method="POST"
enctype="multipart/form-data"
onSubmit="return(validate(this));" // validating user input
novalidate >
....
....
<input name="image" type="file" id="image" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="imageBorder" >
<div id="imageContainer">
<div id="dropbox">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<p> Drop image here or click to upload</p>
</div>
<div id="preview" class="hidden">
</div>
<button id="fileSelect" class="...">Upload Image</button>
<button id="fileRemove" class="...">Remove Image</button>
</div>
</div>
....
....
</form>
Notice that I'm using a hidden input field. Also I have two divs, preview (hidden initially) and dropbox. When an image is uploaded, the class 'hidden' is removed from preview and added to dropbox.
Here is part of the js file newevent.js
$(document).ready(function() {
....
eventImageSetup();
....
}
....
function eventImageSetup() {
var dropbox = document.getElementById("dropbox"),
fileElem = document.getElementById("image"),
fileSelect = document.getElementById("fileSelect"),
fileRemove = document.getElementById("fileRemove");
$(dropbox).height($('#imageBorder').height());
fileSelect.addEventListener("click", function(e) {
if (fileElem) {
fileElem.click();
e.preventDefault(); // to prevent submit
}
}, false);
fileRemove.addEventListener("click", function(e) {
e.preventDefault(); // prevent submit
if(!$('#preview').hasClass('hidden')) { // if there is an image
$('#preview').empty();
$('#dropbox').removeClass('hidden');
$('#preview').addClass('hidden');
$('#fileSelect').text('Upload Image');
$('#image').wrap('<form>').closest('form').get(0).reset();
$('#image').unwrap();
}
removeError($('#imageError'), $('#image'));
});
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
}
function handleFiles(files) {
var file = files[0];
.... // some error checking
var img = document.createElement("img");
img.id = "uploadedImage";
img.file = file;
img.onload = function() {
adjustImageSize(img);
};
$('#dropbox').addClass('hidden');
$('#preview').removeClass('hidden');
$('#preview').empty();
$('#preview').append(img);
$('#fileSelect').text('Replace Image');
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
Here is part of my edit.ejs file
<form action="/events/<%=event._id%>?_method=PUT"
method="POST"
enctype="multipart/form-data"
onSubmit="return(validate(this));"
novalidate >
<input name="image" type="file" id="image" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="imageBorder" >
<div id="imageContainer">
<div id="dropbox" class="hidden">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<p> Drop image here or click to upload</p>
</div>
<div id="preview">
<script>
var imageExists = '<%=event.image%>';
if(imageExists) {
var myImg = document.createElement("IMG");
var source = "../../<%= event.image %>";
myImg.src = source;
adjustImageSize(myImg);
$('#preview').append(myImg);
}
</script>
</div>
<button id="fileSelect" class="...">Upload Image</button>
<button id="fileRemove" class="...">Remove Image</button>
</div>
</div> <!-- END OF imageBorder -->
....
</form>
The script above succesfully makes the image appear in the edit page, as follows.
But when you click submit, the picture doesn't show up.
Here is the nodejs route file. You can see the problem here
// UPDATE SPECIFIC EVENT IN DATABASE
router.put("/:id", upload.single('image'), middleware.checkEventOwnership, function(req, res) {
var filepath = undefined;
if(req.file) {
filepath = req.file.path.substr(7); // Substr to remove "/public"
}
req.body.image = filepath;
Event.findByIdAndUpdate(req.params.id, req.body, function(err, foundEvent) {
if(err) {
console.log(err);
req.flash("error", err);
} else {
req.flash("success", "Successfully edited your event");
}
res.redirect("/events/" + req.params.id);
});
});
Basically, if I leave the image untouched in the edit form, req.file doesn't exist. Thus, req.body.image = undefined. And an image is no longer associated with the event.
Common sense would say do this
if(req.file) {
filepath = req.file.path.substr(7);
req.body.image = filepath;
}
But if you do that, you introduce a new problem: If the user edits the event and removes the image (i.e decides he doesn't want an image associated with the event), the image never gets deleted.
Any idea how to solve this problem? I know I have to do something in the edit.ejs script... More specifically, I need to create an image file... But I'm not sure how to approach this
So I got this to work through a hack I REALLY don't like. I'm sure there is a better, cleaner, standard way of dealing with edit.ejs and images. In other words, please help me find a better solution!
Here are the changes in edit.ejs
<form action="/events/<%=event._id%>?_method=PUT"
method="POST"
enctype="multipart/form-data"
onSubmit="return validate(this) & editPageImageProcessing(this);"
novalidate >
....
....
<div id="preview">
<script>
var imageExists = '<%=event.image%>';
if(imageExists) {
var myImg = document.createElement("IMG");
var source = "../../<%= event.image %>";
myImg.src = source;
myImg.name = "previewImage";
myImg.id = "previewImage";
adjustImageSize(myImg);
$('#preview').append(myImg);
}
</script>
</div>
Basically, I added the lines
myImg.name = "previewImage";
myImg.id = "previewImage";
and added a function editPageImageProcessing.
What this function does is: IF the user didn't upload a new image, and did not delete the image, create a hidden input field "hiddenImage", and let its value be the source of the original image. See below:
// This function deals with edit image
function editPageImageProcessing(form) {
// If the user didn't change the image
// preview would be NOT hidden
// there would not be a req.file (document.getElementById('image').val == '')
// we want a hiddenimage input field
var aFile = document.getElementById('image').value;
console.log("File: ", aFile);
var preview = document.getElementById('preview');
console.log("Preview has hidden class: " + $(preview).hasClass('hidden'));
if(aFile == '' && !$(preview).hasClass('hidden')) {
var input = document.createElement('input');
$(input).attr("name", "hiddenImage");
$(input).attr("id", "hiddenImage");
$(input).attr("type", "hidden");
var myImage = document.getElementById('previewImage');
$(input).attr("value", myImage.src);
$('form').append(input);
}
return true;
}
Now, in the edit route, I did this
// UPDATE SPECIFIC EVENT IN DATABASE
router.put("/:id", upload.single('image'), middleware.checkEventOwnership, function(req, res) {
var filepath = undefined;
if(req.file) { // If user uploaded a new image
filepath = req.file.path.substr(7); // Substr to remove "/public"
console.log(filepath);
} else if(req.body.hiddenImage) { // If user kept the same image
var index = req.body.hiddenImage.lastIndexOf("/uploads");
filepath = req.body.hiddenImage.substr(index);
// req.body.hiddenImage WILL ONLY EXIST if user left image unchanged
}
req.body.image = filepath; // If user deleted image, this will be undefined, which is what we want
Event.findByIdAndUpdate(req.params.id, req.body, function(err, foundEvent) {
if(err) {
console.log(err);
req.flash("error", err);
} else {
req.flash("success", "Successfully edited your event");
}
res.redirect("/events/" + req.params.id);
});
});
Okay, so its messy.
Any better solution would be appreciated

getAsDataURL() doesn't work in chrome and ie

This is my HTML:
<input type="file" id="browse" name="browse" size="" placeholder="Photo" checked="checked" class="upload"/>
<input type="button" onclick="javascript:onbrowse()" class="unknown" value=""/>
And my JavaScript:
$(function() {
$(".upload").change(function () {
var fileObj = $(this).get(0);
var fileName;
if (fileObj.files) {
fileName = fileObj.files.item(0).getAsDataURL()
} else {
fileName = fileObj.value;
}
$(".unknown").css("background-size", "100px 100px");
$(".unknown").css("background-image", "url(" + fileName + ")");
});
});
function onbrowse() {
document.getElementById('browse').click();
}
I have two problems:
onclick doesn't work in Chrome and
getAsDataURL() doesn't work in Chrome and IE
Can you help me?
IE does not yet support the File API. Anyhow, you need to use a FileReader to read a file. Also, the file is not its file name (your variable naming is a little ambiguous).
The click delegation to the file input works just fine.
http://jsfiddle.net/fKQDL/
file = fileObj.files[0];
var fr = new FileReader;
fr.onloadend = changeimg;
fr.readAsDataURL(file);
Bind the button's behavior with jQuery
jQuery('input[type="button"].unknown').click ( onbrowse );

Categories

Resources