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.
Related
This simple form is part of a larger web app I have created. Both the required attributes and the pattern attributes only work intermittently. Changing the event listener to "submit" rather than "click" makes the form validation work properly, but then I get a blank page when I submit with the proper input formatting.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
var process = document.querySelector('input[name="operation"]:checked').value;
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
google.script.run.addEntry(info);
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
document.querySelector('input[name="operation"]:checked').checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
Thanks for the help.
I think I have narrowed the problem down to something to do with the event listener. My thought is that when the "click" event is used, the function runs before the fields are validated by the browser. Yet, I just get a blank page if I use the "submit" event. The function "addEntry" doesn't appear to run; the logged data doesn't appear. Same goes for "addLine" when I add an alert. I have isolated the regex code and verified it works as expected.
Edit: I found that when I remove the event listener on the submit button and add an onsubmit (onsubmit="addLine()") attribute to the form, the alert in "addLine" appears. The "Submitted" alert also appears. Still a blank page after.
Your validation fails but that is outside the scope of the question as I see it since you need to check the actual values before you let it submit and probably need a preventDefault() on the form if any fail.
You get an error because you cannot filter by :checked unless you then determine if that is null OR filter it after you get the nodeList.
Here I show a couple of ways to handle the radio buttons; up to you to determine which suits you.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
//demonstrate a few ways to hanlde the radio buttons:
const procOne = document.querySelector('input[name="operation"]:checked');
console.log(!!procOne ? procOne.value : procOne, typeof procOne); // null and object if none are checked
let processValue = procOne === null && typeof procOne === "object" ? "" : procOne.value;
// querySelectorAll to get all of them so we can filter the list
const processAll = document.querySelectorAll('input[name="operation"]');
// creates an array like object of the nodelist; then filters it for checked ones
const checkProcess = [...processAll].filter(item => item.checked);
console.log("How many?:", processAll.length);
console.log("How many checked?:", checkProcess.length);
console.log(checkProcess.length ? checkProcess.value : "nothing");
// anther way to get value:
processValue = checkProcess.length ? checkProcess.value : "nothing"
if (checkProcess.length !== 0) { //Test if something was checked
console.log(checkProcess.value); // the value of the checked.
} else {
console.log('Nothing checked'); // nothing was checked.
}
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
let process = processValue;
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
//ccommented out as google is not defined
//google.script.run.addEntry(info);
// hitting the DOM again is not a great thing here but left as not part of the question/issue
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
// cannot filter by :checked if none are so check first and set to false
if (procOne != null) procOne.checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
I am trying to push data from a form into an array. I have refresh disabled to allow console.log to show data sets. not sure what I am doing wrong here in my javascript file.
EDIT: ADDING MY VALIDATION CODE FOR CLARIFICATION
class Validate{
constructor(){
console.log("Validate started")
this.formData = [];
document.querySelector("#addbtn").addEventListener("click", e=>this.onClick(e));
}
onClick(e){
const data = document.querySelectorAll("input");
if(this.validateForm(data)){
e.preventDefault();
data.forEach(e=>{
this.formData.push(e.value);
})
} else{
console.log("form not valid");
}
}
validateForm(formData){
let validate = true;
formData.forEach(e=>{
if(!e.checkValidity())
{
validate = false;
}
})
return validate
}
}
(()=>{
const validation = new Validate
})();
class Hero{
constructor(name,email,fanyears,reason){
this.name = name;
this.email = email;
this.fanyears = fanyears;
this.reason = reason;
this.totalfanyears = Utility.calculateyears(this.fanyears);
// this.total = total;
}
}
class Main{
constructor(){
this.listOfHeroes = [];
document.querySelector("#addbtn").addEventListener("click",(e)=>this.add(e));
document.querySelector("#displaybtn").addEventListener("click",(e)=>this.display(e));
}
add(e){
// get data from form
// create a hero from data
// put that hero in the hero array
let name = document.querySelector("#name").value;
let email = document.querySelector("#email").value;
let fanyears = Number(document.querySelector("#fanyears").value);
let reason = document.querySelector("#reason").value;
let hero = new Hero(name,email,fanyears,reason,totalfanyears);
this.listOfHeroes.push(hero);
}
display(e){
for(let i=0; i<this.listOfHeroes.length;i++){
//inner html would go here to put onto web page
console.log(this.listOfHeroes)
}
}
}
(()=>{
const main = new Main();
})();
I will also add my HTML form container code here below :
<div class="flexbox-container">
<div class = "main">
<form id = "heroForm">
<h3> Super Hero Form </h3>
<label for="name">
Name:
<input name="name"id="name" placeholder="Hero name" type ="text" required>
</label>
<label for="email">
Email:
<input name="email" id="email" placeholder="Email Address" type ="email" required>
</label>
<label for="fanyears">
what year did you become a fan?
<input name="fanyears"id="fanyears" placeholder="Amount" type ="number" min=1938 max=2022 step=1 required>
</label>
<label for="reason">
Your reason?
<input name="reason" id="reason" placeholder="Enter info" type ="text" required>
</label>
<button type="submit" id="addbtn">Add hero</button>
<button type="button" id="displaybtn">Display All</button>
</form>
<p id ="message" style = opacity:0>Hero added</p>
</div>
<article class="main">
<h3> Display Results </h3>
<p>
</p>
</article>
</div>
Very confused on how to resolve this or where I am messing up. I have validation that works just fine without this and able to register proper values. regardless of the accuracy of validation not able to retain data and push into the array.
When i do it through my validation fields queryselectorall it works fine pushing into the array.
I'm new to web development and stucked at sending data to server. I have registration form and i want to send this data to server. I can send data from form tag using action and method attribute but it will return response in next page. So i read somewhere i have to use ajax to send data. I tried but i cannot send and capture data using script.
This is my reponse
{"success":true}
Html code
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input id="mobileno" size="40" name="mobileno" type="tel" size="20" maxlength="13" placeholder="Enter your mobile number..." type="number" required><br><br>
<label for="email">Email-Id</label><br>
<input type="text" size="40" id="email" name="email" placeholder="Enter your email-id..." required><br><br>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address" placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country" placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state" placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city" placeholder="Enter your city name....." required><br><br>
<input type="hidden" name="category" value="Individual">
<input type="submit" value="Submit" id="someInput" onclick="ajax_post()"><br>
<p class="small">Institute Registraion</p>
</div>
</div>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "https://smilestechno.000webhostapp.com/Register.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200) {
var resp = console.log(response);
if (resp == "true") {
}
}
hr.send("name="+ name + "&mobileno=" + mobileno + "&email=" + email + "&dob=" + dob + "&address=" + address + "&city=" + city + "&state=" + state + "&country=" + country );
document.getElementById("status").innerhtml = "processing";
}
you can not send variable in this format.
var vars = name+mobileno+email+dob+address+city+state+country;
Params must have a format like:
hr.send("fname=Henry&lname=Ford");
Code you need:
hr.send("name=" + name + "&monbileno=" + mobileno + ... );
You can use jquery to use ajax in a simple way.
Reference:
xmlhttprequest https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
jquery ajax https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Use jquery, it makes it easier. This is how it should be using just the fname and email as an example with jquery ajax:
<form name="myForm" id="myForm" action="myActionUrl" method="POST">
<input type="text" name="fname" id="fname">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$("#myForm").on("submit", function(event){
event.preventDefault(); //this prevents the form to use default submit
$.ajax({
method: "POST",
url: $(this).attr("action"), //this will use the form's action attribute
data: {fname: $("#fname").val(), email: $("#email").val()},
success: function(responseData){
//do something here with responseData
}
});
});
</script>
Please replace the "myActionUrl" part with the url/file that processes your data.
The file can be some basic php file which stores the data into some database and returns or echoes something back so that you can use it within the "responseData" on the ajax success function.
Hope this helps!
Please call function like this
onclick="ajax_post()"
not
onclick="ajax_post"
You used getElementById but selected a name attribute
have to use
getElementById('fname').value;
not
getElementById('name').value;
hey i would recommend using jquery to accomplish this task.
this isthe client script
script type="text/javascript" src='jquery.js'></script>
<!-- download the lates version -->
<script type="text/javascript">
ajax_post(){
var url = "https://smilestechno.000webhostapp.com/Register.php";
var name = $("#name").val();
var mobileno = $("#mobileno").val();
var email = $("#email").val();
var dob = $("#dob").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#state").val();
var country = $("#country").val();
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json',
'url':url,
'data':{name:name,mobileno:mobileno,email:email,dob:dob,address:address,city:city,state:state,country},
'success': function (data) {
tmp = data;
}
});
return tmp; // you can access server response from this tmp variable
}
Server side
<?php
//get items as post inputs
print_r($_POST[]);
echo $_POST['name'];
?>
I'm new to JavaScript and I need to use the string method all in one html page. I need to make sure user input the data, but I can't get my function calling to work. Any idea? I finished all of it, but just to make sure that one button submit can validate all string method function perfectly.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8"/>
<h1> Try 1</h1>
<p>Please enter all the field below.</p>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>String Methods</legend>
<p>Using concat()</p>
<input type="text" id="word1" size="25" placeholder="Enter first word/sentences."></br>
<input type="text" id="word2" size="25" placeholder="Enter second word/sentences."></br></br>
<p>Using substr()</p>
<input type="text" id="subtr" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using lastIndexOf()</p>
<input type="text" id="lastindex" size="25" placeholder="Please enter word/sentences."></br>
<input type="text" id="srch" size="25" placeholder="Word that you want to search."></br></br>
<p>Using toLowerCase()</p>
<input type="text" id="lcase" size="35" placeholder="Please enter Uppercase word/sentences."></br></br>
<p>Using toUpperCase()</p>
<input type="text" id="ucase" size="35" placeholder="Please enter Lowercase word/sentences."></br></br>
<p>Using match()</p>
<input type="text" id="match" size="25" placeholder="Please enter word/sentences."></br>
<input type="text" id="match1" size="25" placeholder="Words that you want to find match."></br></br>
<p>Using replace()</p>
<p id="phrase"><i>The voice in my head shouts out through the world like a breath.</i></p>
<input type="text" id="replce" size="35" placeholder="Word you want to change in sentence above."></br>
<input type="text" id="replce2" size="25" placeholder="Word you want to change with."></br></br>
<p>Using split()</p>
<input type="text" id="splt" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using charCodeAt()</p>
<input type="text" id="cca" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using slice()</p>
<input type="text" id="slce" size="25" placeholder="Please enter word/sentences."></br></br>
<input type="submit" value="Submit" id="btnSubmit" onclick="validateEverything()">
</fieldset>
</form>
<div id="answers"></div>
</body>
</html>
This is my JavaScript code:
<script>
function validateEverything(){
var wo1 = document.getElementById("word1").value;
var wo2 = document.getElementById("word2").value;
var sub = document.getElementById("subtr").value;
var lin = document.getElementById("lastindex").value;
var sea = document.getElementById("srch").value;
var lca = document.getElementById("lcase").value;
var uca = document.getElementById("ucase").value;
var mat = document.getElementById("match").value;
var ma1 = document.getElementById("match1").value;
var phr = document.getElementById("phrase").value;
var rep = document.getElementById("replce").value;
var re1 = document.getElementById("replce1").value;
var ph1 = document.getElementById("phrase1").value;
var spl = document.getElementById("splt").value;
var cha = document.getElementById("cca").value;
var slc = document.getElementById("slce").value;
var ans = document.getElementById("answers");
//Concat
var con = wo1.concat(" "+wo2);
//Subtr
var subr = sub.substring(1, 7);
//lastindexof
var n = lin.lastIndexOf(sea);
//toLowerCase
var lc = lca.toLowerCase();
//toUpperCase
var uc = uca.toUpperCase();
//match
var mc = mat.match(ma1);
//replace
var rp = phr.replace(replce, replce1);
//split
var sp = sp1.split(" ")
//charCodeAt
var cc = cha.charCodeAt(0);
//slice
var sl = slc.slice(1, 5);
show();
}
function show(){
ans.innerHTML = answersHTML();
}
//answers
function answersHTML(){
var ans = document.getElementById("answers").innerHTML;
document.write(con);
document.write(subr);
document.write(n);
document.write(lc);
document.write(uc);
document.write(mc);
document.write(rp);
document.write(sp);
document.write(cc);
document.write(sl);
}
</script>
There are multiple issues in your snippet.In some case there is no DOM element present but still you are doing document.getElementById();
Also how answerHTML will know about con,sub,.... ? They are local to validateEverything function & you are not passing it to answerHTML function
You are using input type = "submit". You need to use event.preventDefault() to stop submission. You are not submitting anything. Rather use input type = "button"
There is also no use of show() function
Everytime you are using document.write, so it will delete anything which is previously written. Instead string concatenation and innerHTML will be fine.
Here is a working snippet with minimum code.
JS
function validateEverything(event){
event.preventDefault();
var wo1 = document.getElementById("word1").value;
var wo2 = document.getElementById("word2").value;
var sub = document.getElementById("subtr").value;
var ans = document.getElementById("answers");
//Concat
var con = wo1.concat(" "+wo2);
//Subtr
var subr = sub.substring(1, 7);
ans.innerHTML = con+" "+subr;
}
HTML
<input type="submit" value="Submit" id="btnSubmit" onclick="validateEverything(event)">
JSFIDDLE
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.