I made some little project with adding element to DOM. It's working but I don't know how to clear form after submit. I need to assign a blank value? At what point? Sorry, Im new, please don't bite. Thanks.
const addElement = (e, node, txt, attr, value) => {
e.preventDefault();
const element = document.createElement(node);
if(txt){
const text = document.createTextNode(txt);
element.appendChild(text);
}
if(attr){
element.setAttribute(attr, value)
}
document.querySelector('.content').appendChild(element);
}
const addForm = document.querySelector('.form--add');
addForm.addEventListener('submit', (e) => addElement(
e,
addForm.elements.node.value,
addForm.elements.text.value,
addForm.elements.attr.value,
addForm.elements.value.value,
));
<div class="form-container">
<form class="form form--add">
<h1 class="form__title">Add element to DOM</h1>
<input type="text" class="form__input" name="node" placeholder="element html" required>
<input type="text" class="form__input" name="text" placeholder="txt in element html">
<input type="text" class="form__input" name="attr" placeholder="attr" required>
<input type="text" class="form__input" name="value" placeholder="attr value" required>
<button class="form__button">Add element</button>
</form>
<form class="form form--search">
<h1 class="form__title">Search DOM</h1>
<input type="text" class="form__input" placeholder="szukana nazwa elementu" required>
<input type="submit" class="form__button" value="znajdź i pokaż informacje">
</form>
</div>
<div class="result"></div>
<div class="content"></div>
<footer class="footer">Stopka</footer>
<script src="main.js"></script>
Thank you
Try addForm.reset()
or
declare an id for suppose form_id then paste below code after submit
document.getElementById("form_id ").reset();
addForm.addEventListener('submit', (e) => addElement(
e,
addForm.elements.node.value,
addForm.elements.text.value,
addForm.elements.attr.value,
addForm.elements.value.value,
addForm.getElementsByTagsName('input').forEach(el => {
el.value = ''
})
));
Related
Example Form So Far
This is my current code that works, without any checkbox handling started.
import React, { useState } from "react";
import "../admin/SysHealthForm.scss";
export default function SysHealthForm() {
const [input, setInput] = useState({
header: "",
content: "",
eta: "",
});
//When any change is registered, update the Name + Value with target.
//Return previous text and display as name: entered value
function handleChange(e) {
const { name, value } = e.target;
setInput((prevInput) => {
return {
...prevInput,
[name]: value,
};
});
}
//Stop Page Refreshing and Console.log the JSON
function handleClick(e) {
e.preventDefault();
console.log(input);
}
return (
<div className="widgit-syshealth">
<h2>System Health</h2>
<form>
<input
name="header"
placeholder="Header"
autoComplete="off"
onChange={handleChange}
value={input.header}
required
></input>
<textarea
name="content"
placeholder="Message"
autoComplete="off"
onChange={handleChange}
value={input.content}
required
></textarea>
<div className="form-school-check">
<div>
<input type="checkbox" id="syshpcb1" value="Fosseway"></input>
<label htmlFor="syshpcb1">Fosse Way</label>
</div>
<div>
<input type="checkbox" id="syshpcb2" value="Mendip"></input>
<label htmlFor="syshpcb2">Mendip</label>
</div>
<div>
<input type="checkbox" id="syshpcb3" value="Nunney"></input>
<label htmlFor="syshpcb3">Nunney</label>
</div>
<div>
<input type="checkbox" id="syshpcb4" value="Hayesdown"></input>
<label htmlFor="syshpcb4">Hayesdown</label>
</div>
<div>
<input type="checkbox" id="syshpcb5" value="Moorlands"></input>
<label htmlFor="syshpcb5">Moorlands</label>
</div>
<div>
<input type="checkbox" id="syshpcb6" value="Cameley"></input>
<label htmlFor="syshpcb6">Cameley</label>
</div>
<div>
<input type="checkbox" id="syshpcb7" value="St Mary's"></input>
<label htmlFor="syshpcb7">St Mary's</label>
</div>
<div>
<input type="checkbox" id="syshpcb8" value="Other"></input>
<label htmlFor="syshpcb8">Other</label>
</div>
</div>
<input
placeholder="ETA For Fix"
onChange={handleChange}
value={input.eta}
name="eta"
></input>
<button type="Submit" onClick={handleClick}>
Submit
</button>
</form>
</div>
);
}
At The Moment, when you submit the data. It logs the header, content and eta etc correctly
but i want it to essentially create an Array of all the checkboxes that are ticked.
I just don't know where i would even begin..
Will be pushing the data back up to a MongoDB Atlas database once recieved.
Thanks
I'm working on registration form that has three sections. A user moves to the next section of the form when the button "Next" is clicked. Everything is working well except that validation errors are only showing on the last section of the Form. I would like to validate the form before moving to the next section. For now, when "Next" button is clicked, the user can move to the next section even without filling the fields. I'm not so experienced in JavaScript, please help.
HTML:
<section>
<div class="container">
<form>
<div class="step step-1 active">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="first-name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="last-name">
</div>
<div class="form-group">
<label for="nickName">Nick Name</label>
<input type="text" id="nickName" name="nick-name">
</div>
<button type="button" class="next-btn">Next</button>
</div>
<div class="step step-2">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" name="email">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="number" id="phone" name="phone-number">
</div>
<button type="button" class="previous-btn">Prev</button>
<button type="button" class="next-btn">Next</button>
</div>
<div class="step step-3">
<div class="form-group">
<label for="country">country</label>
<input type="text" id="country" name="country">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" name="city">
</div>
<div class="form-group">
<label for="postCode">Post Code</label>
<input type="text" id="postCode" name="post-code">
</div>
<button type="button" class="previous-btn">Prev</button>
<button type="submit" class="submit-btn">Submit</button>
</div>
</form>
</div>
</section>
JavaScript:
const steps = Array.from(document.querySelectorAll("form .step"));
const nextBtn = document.querySelectorAll("form .next-btn");
const prevBtn = document.querySelectorAll("form .previous-btn");
const form = document.querySelector("form");
nextBtn.forEach((button) => {
button.addEventListener("click", () => {
changeStep("next");
});
});
prevBtn.forEach((button) => {
button.addEventListener("click", () => {
changeStep("prev");
});
});
form.addEventListener("submit", (e) => {
e.preventDefault();
const inputs = [];
form.querySelectorAll("input").forEach((input) => {
const { name, value } = input;
inputs.push({ name, value });
});
console.log(inputs);
form.reset();
});
function changeStep(btn) {
let index = 0;
const active = document.querySelector(".active");
index = steps.indexOf(active);
steps[index].classList.remove("active");
if (btn === "next") {
index++;
} else if (btn === "prev") {
index--;
}
steps[index].classList.add("active");
}
If you want to validate one section of the form before moving on to the next one you should do something like this:
nextBtn.forEach(button => {
button.addEventListener("click", () => {
handleEvent("next")
})
})
prevBtn.forEach(button => {
button.addEventListener("click", () => {
handleEvent("prev")
})
})
where handleEvent is:
function handleEvent(btn) {
if (!handleFormValidation(btn)) return "error message here";
changeStep(btn)
}
Here handleFormValidation would be a function that checks weather the input is correct and returns true if it is and false if it isn't
If you want to make sure the user fills in the first form first before going to the second you can do it by making the second form appear only after the next button is pressed, but that would require a major rework of your system. (i do however advise it because when i copied your code to test it i noticed quite a lot of bugs)
Here are some mdn articles describing how to make, delete and append elements using javascript:
making an element
removing an element
removing an element
appending an element to another element
appending an element to another element
I highly encourage you to do your own research as well.
I also just want to apologise if anything in my answer isn't understandable. I'm new at contributing to this community so there will likely be mistakes I've made.
I can't figure out how to connect function that will save name and surname in local storage and go to the other page. If you could point out the problem I would be very grateful :)
index.html
<form id="from" action="" method="post">
<div>
<pre> <label for="name">Име</label></pre>
<input id="name" name="name" type="text" required>
<br>
<pre><label for="surname"> Презиме </label></pre>
<input id="surname" surname="surname" type="text" required>
<br><br>
</div>
<button onclick="sumbit()"> Започни тест </button>
</form>
script.js
let infs = [];
const addInf= (ev)=>{
ev.preventDefault(); //to stop the form submitting
let inf = {
id: Date.now(),
name: document.getElementById('name').value,
surname: document.getElementById('surname').value
}
infs.push(inf);
document.forms[0].reset(); // to clear the form for the next entries
//saving to LS
localStorage.setItem('MyInfList', JSON.stringify(infs) );
}
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById('btn').addEventListener('click', addInf);
});
Try this, use window.location for redirecting to another page, it has same functionality as href.
<form id="from" action="" method="post">
<div>
<pre> <label for="name">Име</label></pre>
<input id="name" name="name" type="text" required>
<br>
<pre><label for="surname"> Презиме </label></pre>
<input id="surname" surname="surname" type="text" required>
<br><br>
</div>
<a><button id="btn"> Започни тест </button> </a>
</form>
<script>
let infs = [];
const addInf = (ev) => {
ev.preventDefault(); //to stop the form submitting
let inf = {
id: Date.now(),
name: document.getElementById('name').value,
surname: document.getElementById('surname').value
}
infs.push(inf);
//saving to LS
localStorage.setItem('MyInfList', JSON.stringify(infs));
document.forms[0].reset(); // to clear the form for the next entries
window.location = "quiz.html"
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addInf);
});
</script>
In my app I collect information from the user and store it in Local storage using javascript like this.
Event Name (1 to 20 characters):
<input type="text" id="eventname" name="eventname" required
minlength="1" maxlength="20" size="20">
<label for="datetime">Event Date and Time:</label>
<input type="datetime-local" id="date" name="date" required
minlength="1" maxlength="20" size="20">
<label for="eventlocation">Event Location (1 to 20 characters):</label>
<input type="text" id="location" name="location" required
minlength="1" maxlength="20" size="20">
<label for="notes">Notes (0 to 50 characters): </label>
<input type="text" id="notes" name="notes" required
minlength="0" maxlength="50" size="50">
<script src="app.js"></script>
I then have an app.js document which puts it into local storage
const locationTxt = document.querySelector('#location');
locationTxt.addEventListener('change', (event) => {
localStorage.setItem('location', event.target.value);
function getSavedData() {
console.log('location', localStorage.getItem('location'));
(except i have these fucntions for each of the inputs.)
How Would i go about taking all these inputs in locale storage and displaying it as 1 event that is able to be categorized by time?
One way would be to store event data in an object:
{
'01-02-1900': [
... // Array of events
],
'01-01-1900': [
... // Array of events
],
...
}
And then using JSON.parse and JSON.stringify to read/write to localStorage. 😊
For instance:
/**
* This override localStorage in Stack Snippet
*/
const customStorage = { data: {} };
customStorage.getItem = index => customStorage.data[index] || null;
customStorage.setItem = (index, payload) =>
(customStorage.data[index] = payload);
/**
* Replace customStorage with localStorage below.
*/
const inputs = document.querySelectorAll("input");
const storageIndex = "myTestStorage";
const storeInLocal = formData => {
const { date, event } = formData;
const toStore = JSON.parse(customStorage.getItem(storageIndex)) || {};
if (!toStore[date]) toStore[date] = [];
toStore[date].push(event);
customStorage.setItem(storageIndex, JSON.stringify(toStore));
};
const readForm = () => {
let values = {};
inputs.forEach(({ name, value }) => {
values[name] = value;
});
const { date, eventname, location, notes } = values;
return {
date,
event: {
eventname,
location,
notes
}
};
};
const outputStorage = () => {
const storage = customStorage.getItem(storageIndex) || "";
document.getElementById("output").innerText = storage;
};
document.getElementById("eventForm").addEventListener("submit", e => {
e.preventDefault();
const formData = readForm();
storeInLocal(formData);
outputStorage();
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Store form data in localStorage</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
rel="stylesheet"
/>
<style>
pre {
white-space: pre-wrap;
}
</style>
</head>
<body>
<main id="app" role="main" class="container">
<form id="eventForm">
<div class="form-group row">
<label for="eventname">Event Name</label>
<div class="col-sm-6">
<input
type="text"
id="eventname"
name="eventname"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="datetime">Event Date and Time:</label>
<div class="col-sm-6">
<input
type="datetime-local"
id="date"
name="date"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="eventlocation">Event Location</label>
<div class="col-sm-6">
<input
type="text"
id="location"
name="location"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="notes">Notes</label>
<div class="col-sm-6">
<input
type="text"
id="notes"
name="notes"
required
minlength="0"
maxlength="50"
/>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<h1 class="h4">Output</h1>
<p>Hit "save" multiple times, and change the date occasionally.
<p>
<pre id="output"></pre>
</p>
</main>
</body>
</html>
I have an existing json file (data.json) that I would like to append with information captured from a form.
I have the form outputting json but I am not sure how to go about getting this to add to my existing json file.
So the form looks like this:
<form id="test" action="#" method="post">
<div class="form-group">
<label for="department">Department:</label>
<input class="form-control" type="text" name="department" id="department" />
</div>
<div class="form-group">
<label for="role">Role title:</label>
<input class="form-control" type="text" name="role" id="role" />
</div>
<div class="form-group">
<label for="pay_status">Pay status:</label>
<input class="form-control" type="text" name="pay_status" id="pay_status"/>
</div>
<div class="form-group">
<label for="typicalposts">Typical number of posts in a year:</label>
<input class="form-control" type="text" name="typicalposts" id="typicalposts"/>
</div>
<div class="form-group">
<label for="email">Restrictions:</label>
<input class="form-control" type="text" name="restrictions" id="restrictions" />
</div>
<div class="form-group">
<label for="recruitment_date">Recruitment date:</label>
<input class="form-control" type="date" name="recruitment_date" id="recruitment_date" />
</div>
<div class="form-group">
<label for="weblink">Weblink:</label>
<input class="form-control" type="text" name="weblink" id="weblink" />
</div>
<div class="text-center">
<p>
<input type="submit" value="Send" class="btn btn-primary center_block" />
</p>
</div>
</form>
<pre id="output" ></pre>
And the js I have to turn this data to json is:
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
var output = document.getElementById( "output" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
output.innerHTML = json;
}, false);
});
})();
This shows the json in #output for the moment, I would like what is being shown here to be appended to data.json instead
Thanks for your help
My files are hosted on a server that I dont have access too which is why I would like to do this via js
So BBC News have an HTML document at http://www.bbc.co.uk/news. Would it be a good idea if it was possible for my browser to edit the page and save it back to the server?
It is absolutely impossible to do what you want, because it would require that any old browser could edit any old file on any old server.
In order to change data on the server, you have to have the cooperation of the server (which you say you don't have).