How to save web application input data in the same web location? - javascript

I would like to save input data from web application in the same web location where the .html file placed. The saved file should be over ride with the new data every time we click the button. Currently, code downloads file to local. How to place the file in the web location and it should be over ride with new data?
Code:
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button]{
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<!--Add few elements to the form-->
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</div>
</body>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
// This variable stores all the data.
let data =
'\r Name: ' + name.value + ' \r\n '
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.txt'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
</script>
</html>

Javascript doesn't allow save or read files locally without user's consent (aka download/upload). If you need store data for your website/application, you can use WebStorage instead.

Related

How to add bg image to API weather project?

Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly

JavaScript input alerts user

I have the code below and what it currently does is if the user types index.html it will bring the to index.html etc. But what I want is if they type in a file that doesn't exist it alerts them. For example, they type hi.html and hi.html doesn't exist, it will then alert them saying the file doesn't exist.
The code:
let btn = document.querySelector('.ex');
let inputPath = document.querySelector('.path');
// redirect to chosen path
btn.addEventListener('click', function() {
location.href = inputPath.value;
});
<input type='text' class='path' style="color: #222; background: white; padding: 5px; border-radius: 6px; border: none;">
<br><br><input type="submit" class="ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;" />
you'd have to check against your available files to see if it's there. For example,
let files = ['index.html', 'hello.html']
Then, in your event listener, you only allow valid files to reassign location.href. For the rest, you could send an alert. For example,
if (files.some((file) => file == inputPath.value)) {
location.href = inputPath.value
} else {
alert('Not a valid path.')
}

Save contentEditable into html file with javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

I want to save textbox to .txt file in HTML using JavaScript but I have an error

I have a fake web site for a school project and I want to get the HTML code to send the information from textbox to .txt file with Javascript, but it doesn't work and I don't know why. Can you tell me where the error is, please?
<section>
<form method:"POST">
<label>Escrigui el seu usuari:</label>
<input type="text" name="usuari" id="usuari" size="20"/>
<label>Escrigui la seva contrasenya:</label>
<input type="text" name="contrasenya" id="contrasenya" size="20"/>
<input type="button" value="submit" id="button" href="" onclick="WriteToFile()"/>
</form>
<script type="text/javascript">
function WriteToFile(passForm){
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("filename.txt", True);
var usuari = document.getElementById("usuari").value;
var contrasenya = document.getElementById("contrasenya").value;
s.writeline("usuari :" + usuari);
s.writeline("contrasenya :" + contrasenya);
s.writeline("-----------------------------");
s.Close();
}
</script>
I've programmed a "Notebook" that exports the input to a txt file which is ready to be downloaded after:
<html><head>
<style>
body {
margin: 0%;
}
#font-face {
font-family: "CG";
src: url(./resources/CENTURYGOTHIC.ttf) format("truetype");
}
textarea {
margin-left: 0%;
margin-top: 0%;
height: 80%;
width: 100%;
resize: none;
visibility: visible;
background-color: white;
border-color: black;
}
button {
background-color: white;
font-family: CG;
border-color: black;
border-width: 1px;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 20px;
padding-left: 20px;
margin-top: 10px;
text-transform: capitalize;
}
</style></head>
<body>
<textarea id="textbox" placeholder="You can write anything here... just start tyipng what you would like to remember: Notes, Homework, Tests, just anything."></textarea>
<button id="create">SAVE TO FILE</button>
<a download="notes.txt" id="downloadlink" style="display: none"><button onclick="functionreset()">DOWNLOAD</button></a>
<br>
<script>
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
document.getElementById('create').style.display = 'none';
}, false);
})();
function functionreset() {
var link = document.getElementById('downloadlink');
link.style.display = 'none';
document.getElementById('create').style.display = 'block';
}
</script>
<script>
document.getElementById("textbox").onchange = function() {functionreset()}
</script>
<!-- <iframe height=100% width=100%; src=./test.html></iframe>-->
</body></html>
maybe you can use fragments of this...
Notify me if it worked😉

Setting.a variable from an input type, changing it, then load as a URL

I'm trying to make it so that you can:
(achieved) 1. enter a url into the input form
2. add a prefix and postfix of my choice to the url (prefix = "http://"; postfix = "/postfixtexthere")
3. load the complete url (or value 'urlToLoad') into a web browser
I'm not sure if the variable 'urlToLoad' is correct or not because the 2nd alert doesn't work despite the 1st alert working.
My questions are as follows:
1. Is the variable 'urlToLoad' correct? Does it adapt to what's entered in the input box?
2. How can I then get the variable 'urlToLoad' to load as a website in a web browser?
Hopefully I've done most of the work already. Thanks for the advice.
function checkDomain() {
alert('function executed successfully');
var testInput = document.getElementById("checker");
var testUrl = textInput.value;
var urlToLoad = "http://" + testUrl + "/postfixtexthere";
alert(urlToLoad);
// instructions
// var urlToLoad = PUT VAR ‘testUrl’ INTO THIS URL, REPLACING ‘__________’: http://__________/postfixtexthere
// THEN LOAD THE URL AS A LINK IN A WEB BROWSER
}
.cta-button, a.cta-button {
border-radius: 6px;
padding: 10px 20px;
border: 1px solid #393939;
cursor: pointer;
background: #ff0;
display: inline-block;
text-align: center;
}
<p>text above the input type</p>
<div id="misc">
<input type="text" placeholder="Enter url" id="checker" value="thisdomain">
</div>
<a class="cta-button" onclick="checkDomain()">Check Link</a>
Try to run this in your local and it should open the URL in new window
function checkDomain() {
alert('function executed successfully');
var testInput = document.getElementById("checker");
var testUrl = document.getElementById('checker').value;
var urlToLoad = "https://" + testUrl + "/postfixtexthere";
alert(urlToLoad);
window.open(urlToLoad);
// instructions
// var urlToLoad = PUT VAR ‘testUrl’ INTO THIS URL, REPLACING ‘__________’: http://__________/postfixtexthere
// THEN LOAD THE URL AS A LINK IN A WEB BROWSER
}
.cta-button, a.cta-button {
border-radius: 6px;
padding: 10px 20px;
border: 1px solid #393939;
cursor: pointer;
background: #ff0;
display: inline-block;
text-align: center;
}
<p>text above the input type</p>
<div id="misc">
<input type="text" placeholder="Enter url" id="checker" value="thisdomain">
</div>
<a class="cta-button" onclick="checkDomain()">Check Link</a>

Categories

Resources