HTML User Input to local file location - javascript

I'm trying to create a form with HTML and javascript to be able to retrieve 3 different inputs from the user, combine them into 1 form in json format, and save the file into a local file location. Below is what I currently have. (I am unclear how I am able to save a json string to a local file location. Thank you for your time in advance. (I am a javascript and html novice)
<header class="banner">
<h1 style="color:blue">HTML User Input to local file location</h1><main>
<form id="myform" type="post">
<fieldset>
<legend style="color:blue">Sign Up</legend>
<p style="color:red">Write your con-fig codes below</p>
<div class="elements">
<label for="Input1">Input1 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input1"
name="Input1" size="25" />
</div>
<div class="elements">
<label for="Input2">Input2 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input2"
name="Input2" size="25" />
</div>
<div class="elements">
<label for="Input3">Input3 :</label>
<input required="required" type="text" onfocus="this.value=''" value="Input3"
name="Input3" size="25" />
</div
<div class="submit">
<input type="submit" id="btn" name="submit" class="btn" value="Send" />
</div>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function(e) {
var jsonData = {};
var formData = JSON.stringify($("#myForm").serializeArray());
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
e.preventDefault();
});
});
</script>
</main>

This has definitely been asked before in multiple places. Like Here and Here. Code copied from one of the links below
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Credit to #Rafał Łużyński.
Please search for the solutions better before actually asking a question.

Related

Form submit to specific url according to data inserted

I have a form that is simply a input with a zip code and a submit button.
I need some help on submitting the form according to the data inserted.
For example if someone inserts a number between 1000-000 and 2999-999 it will be forward to landing1.html, if the input is between 3000-000 to 4000-999 it will forward to landing2.html and so on.
This is a draft of my code my code for better understanding
$(document).ready(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>
Hope someone can help me.
Many thanks!
Like this
We can make it more complex if you have many sets of post codes
$(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
$(".needs-validation").on("submit",function() {
const cp = this.cp.value;
if (cp >= "1000-000" && cp <= "2999-999") this.action = "landing1.html";
else if (cp >= "3000-000" && cp <= "4000-999") this.action = "landing2.html";
// else this.action = "outofrange.html";
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>

form data not saving to chrome local storage

I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?
function submit() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var feedback = document.getElementById("feedback").value;
localStorage.setItem("name", name);
localStorage.setItem("email", email);
localStorage.setItem("feedback", feedback);
return true;
}
function init() {
var name = localStorage.getItem("name");
var email = localStorage.getItem("email");
var feedback = localStorage.getItem("feedback");
document.write("passed value = " + name);
document.write("passed value = " + email);
document.write("passed value = " + feedback);
}
HTML
<form action="form.html" method="get" onsubmit="submit()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
<script src="form.js" type="text/javascript"></script>
You have created a very pesky and hard to find bug there!
No it's not the event doubling in <input type="submit" value="Submit" onclick="submit()"> <input type="submit" value="Submit" onclick="submit()">
even though it can be considered a bad practice
Spot it?
it's submit()!
Try this and submit the form
<form action="form.html" method="get" onsubmit="alert(getAttributeNames()); submit()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
Surprised eh? You haven't defined getAttributeNames() anywhere yet it works! How is that you ask??
This is because it is one of many inbuilt DOM method that every html element inherits. Now you get the idea what happened when you used onsubmit="submit()" It didn't call the submit() function you wrote instead it called the inbuilt submit (form's native) method that submits it to server and once it submits obviously it won't do any localstorage business
The fix is simple just use names that won't collide with the built-in(s). Or you can also use addEventListener() because in that you can tell browser explicitly "no, use this function that I've written not the inbuilt one, please"
Here is a fixed version I just changed the name of your function
<form action="form.html" method="get" onsubmit="submit2()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
<script>
function submit2() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var feedback = document.getElementById("feedback").value;
localStorage.setItem("name", name);
localStorage.setItem("email", email);
localStorage.setItem("feedback", feedback);
return true;
}
function init() {
var name = localStorage.getItem("name");
var email = localStorage.getItem("email");
var feedback = localStorage.getItem("feedback");
document.write("passed value = " + name);
document.write("passed value = " + email);
document.write("passed value = " + feedback);
}
</script>
The thing is that localstorage cannot store objects, but you could always store json formatted objects as a string and parse it later whenever you want to you the data!
And also the form submission should be stopped before it refreshes the page! just by adding the return false on the onsubmit event.
<form action="form.html" method="get" id="myForm">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<script>
var myForm = document.querySelector("form#myForm");
myForm.onsubmit = function(){
const data = {};
const dataToFetch = this.querySelectorAll("input, textarea, button, select");
for(let element of dataToFetch){
if( element && element.tagName && element.name )
data[element.name] = element.value;
}
let jsonData = JSON.stringify( data );
localStorage.setItem("formData", jsonData);
alert("Data stored to localStorage itemName:'formData'");
return false;
}
</script>
I use a function for this so I can call it at any time.
// add to local storage
const addToLocalStorageObject = function (name, key, value) {
// Get the existing data
let existing = localStorage.getItem(name);
// If no existing data, create an object
// Otherwise, convert the localStorage string to an object
existing = existing ? JSON.parse(existing) : {};
// Add new data to localStorage object
existing[key] = value;
// Save back to localStorage via stringify
localStorage.setItem(name, JSON.stringify(existing));
};
// retrieve from local storage
const retrieveFromLocalStorageObject = function (name) {
let data = localStorage.getItem(name);
// read the localStorage item and convert it to an object
return data ? JSON.parse(data) : null;
};
Then call addToLocalStorageObject('name', name);
And retrieveFromLocalStorageObject('name');
NB: I did not write the above functions but I have found them extremely useful.

400 bad request in graphql

I am trying to insert a new product through a form with javascript into database in grapqhl server and also that product should be displayed in zonaB with javascript ,but i am getting the error 400 bad request. Could someone tell me where is the mistake
here is html code
'''
<form id="formular" action="#" method="POST">
<label>Numar produs:</label>
<input type="text" id="nr">
<label>Denumire produs:</label>
<input type="text" id="nume" ><br>
<label>Categorie produs: </label>
<input type="text" id="categorie"> <br>
<label>Descriere: </label>
<input type="text" id="descriere"><br>
<label>Imagine:</label>
<input type="text" id="imagine"><br>
<label> Pret:</label>
<input type="text" id="pret"><br>
<label> Disponibil:</label>
<input type="text" id="stoc"><br>
<button onmouseover="insereaza1()"> Insereaza</button>
</form>
<script>
var $id = $('#nr').val()
var $name = $('#nume').val()
var $id_categorie = $('#categorie').val()
var $descriere = $('#descriere').val()
var $imagine = $('#imagine').val()
var $pret = $('#pret').val()
var $stoc = $('#stoc').val()
function insereaza1() {
creareProdus={"query":"mutation{createProduct($id:ID!, $name:String, $id_categorie:ID,
$descriere:String, $imagine:String, $pret:Float, $stoc:Boolean){createProduct(id:$id,
name:$name, category_id:$id_categorie, description:$descriere, picture:$imagine,
price:$pret, available:$stoc){product{id }}}}"}
setari={url:"http://localhost:3000",
type:"POST",
data:creareProdus,
contentType:"application/json",
success:vizualizareProdus}
$.ajax(setari)
}
function vizualizareProdus(){
var x = document.getElementById("formular").method
document.getElementById("zonaB").innerHTML = x
}
</script>
</body>
</html>
'''

How to check if input name is inside an array in Jquery?

I want to know how I can check if input name is equal to name inside an array.
I have multiple inputs like below code:
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
And I have an array Like this:
var array = ['last_name', 'email'];
I want to add class to div, that wrap the input his name inside the array.
I don't want to use 2 loops.
You can use the following code:
var inputs = $("input");
var array = ['last_name', 'email'];
inputs.each(function(){
if(array.indexOf($(this).attr("name")) >= 0){
alert($(this).attr("name")+" exists");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
The HTML to the code is same as used by you in your question, I have added a bit of JQuery, that is simple to understand.
I hope it was helpful.
check output in browser console:
$(document).ready(function() {
var array = ['last_name', 'email', 'dsfdsfds'];
array.forEach(function(element) {
var x = document.getElementsByName(element);
console.log(x);
});
});
//check output in browser console
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
there is your solution :)
$(document).ready(function() {
var array = ['last_name', 'email'];
var inputs = $("div[class='inputMain']").find("input");
array.forEach(function(name) {
inputs.each(function (x){
if (inputs[x].name === name) {
inputs[x].parentNode.classList.add("myClass")
}
});
});
console.log(inputs.prevObject);
});
https://jsfiddle.net/12es37ko/62/
you can check result into browser console :)

multiple forms with javascript

I am trying to show forms according to user input in the text box but it is showing it one time only...please help...
index.html:
<html>
<head>
<script type="text/javascript" src="demo1.js"></script>
</head>
<body>
<form name="su">
<input type="text" name="tt" onkeyup="javascript:toggleFormVisibility();" id="sub"/> </a>
</form>
<form id="subscribe_frm" style="display:none">
NAME:<input type="text" name="text">
EMAIL:<input type="text" name="text">
PASSWORD:<input type="text" name="text">
</form>
demo.js:
function toggleFormVisibility()
{
var txt = document.getElementById('sub').value;
for(var i=0;i<txt;i++)
{
var frm_element = document.getElementById('subscribe_frm');
var vis = frm_element.style;
vis.display = 'block';
}
}
A bit of a guess, but I think you are trying to create multiple copies of your form. Try this out:
http://jsfiddle.net/QnrM9/
JS
function toggleFormVisibility() {
var txt = document.getElementById('sub').value;
var neededChildren = txt.length - document.getElementById('form_container').children.length + 1;
for (var i = 0; i < neededChildren; i++) {
var frm_element = document.getElementById('subscribe_frm').cloneNode(true);
var vis = frm_element.style;
vis['display'] = 'block';
document.getElementById("form_container").appendChild(frm_element);
}
}
document.getElementById('sub').addEventListener('keyup', toggleFormVisibility);
HTML
<form name="su">
<input type="text" name="tt" id="sub" />
</form>
<div id="form_container">
<form id="subscribe_frm" style="display:none">NAME:
<input type="text" name="text" />EMAIL:
<input type="text" name="text" />PASSWORD:
<input type="text" name="text" />
</form>
</div>

Categories