How to save input in an array then add to saved input - javascript

I am creating a form with two text boxes: Task and Description. What I want to do is be able to console.log in both boxes and save the input through a submit button.
i.e:
task: do laundry
Description: do a buttload of laundry(idk lol)
Alright, I got that down(I think). But what I want to do after is that once I backspace and clear it, I want to add another task and description, but I also want to add that AFTER the saved input.
ie:
task: do laundry, study
Description, do a buttload of laundry, study a lot
Can someone check my code and see what's wrong? It's just showing the console.log input, which is nice, but I want to be able to use the push method to add to the end of my arrays and SAVE it.
function submitForm() {
var FormData = {
task: myForm.task.value,
description: myForm.description.value
};
myJSON = JSON.stringify(FormData);
localStorage.setItem("formJSON", myJSON);
text = localStorage.getItem("formJSON");
obj = JSON.parse(text);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(task);
console.log(" " + descriptionArray.join(", "));
}
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit=" return submitForm()">
<label class="required">*Task and Description* </label>
<!first text box>
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!second comment box>
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script type="text/javascript " src="json.js "></script>
</div>
</p>
</form>
</body>
</html>
All tasks and description has to be in array form and packaged in JSON.

You just need to call your addTask and addDescription functions when the form submits. JSFiddle: http://jsfiddle.net/wcrg804z/
Some errors with your code:
You have two addTask functions when you only need one.
Your addDescription function is trying to push task (which is undefined) to descriptionArray.
There are extra closing </div> </p> </form> tags after your form which are unnecessary.
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit="return submitForm()">
<label class="required">*Task and Description* </label>
<!--first text box-->
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!--second comment box-->
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script>
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
//myJSON = JSON.stringify(FormData);
//localStorage.setItem("formJSON", myJSON);
//text = localStorage.getItem("formJSON");
//obj = JSON.parse(text);
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(description);
console.log(" " + descriptionArray.join(", "));
}
</script>
</body>
</html>

Related

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

Simple if statement inside jquery $.each function not returning right value

I'm unable to get a basic if statement inside a jquery $.each loop working. I have a json object that I loop through, and if the value entered in a text box is found in the json object, I return a flag I set as false. But for some reason, the if statement is not executing. Here is the code:
var authorlist = [
{"AUTHOR":"DONNA EDWARDS","COUNTRY":"USA","REGION":"MIDWEST"},
{"AUTHOR":"EMERALD JONES","COUNTRY":"UK","REGION":"EU"},
{"AUTHOR":"SHAKESPEARE","COUNTRY":"UK","REGION":"EU"}];
function checkName() {
var nameIsValid = true;
var nametocheck = $("#name").val();
$.each(authorlist, function(index, val){
//console.log(val.AUTHOR);
if(nametocheck == val.AUTHOR) {
//console.log(val.AUTHOR);
nameIsValid = false;
return false;
}
});
return nameIsValid;
}
$("#btnCheck").on("click", function(){
console.log("The name entered is valid: " + checkName());
});
<form class="form-horizontal" name="paymentInformation" id="paymentInformation" action="verifyOrder.cfm" method="post" role="form">
<div class="form-group">
<fieldset class="col-sm-12">
<!-- Row 1 -->
<div class="row">
<div class="col-sm-6">
<label for="id2" class="col-6 col-form-label">
Book Name
</label>
<input type="form-control" placeholder="Book Name" type="text" id="id2" name="id2" class="col-10">
<button type="button" class="btn btn-primary" id="btnCheck">Check</button>
</div>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
https://jsfiddle.net/wqnkz4v7/
Edit following
var nametocheck = $("#id2").val();
or Use following
$("input[name='name']").val();
You need to address the right id.
var nametocheck = $("#id2").val();
// ^^^^
The error you have is in var nametocheck = $("#name").val();.
The selector according to the html should be "#id2".

Array of html inputs

I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/

Creating a dynamic form with input buttons

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.

Replace innerhtml on form submit with javascript

I want to have a form that asks the user their name, then welcomes them to the website with that name without redirecting to a different page or reloading. So basically replace a form with "Welcome NAME" after submit is clicked.
My code:
<div id="welcomeText">
<form onsubmit="changeText()" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById(welcomeForm).fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
You need to give a name to the form before trying to access it, something like this:
//create the name attribute for the form
<form onsubmit="changeText()" method="post" name="myForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<script>
function changeText() {
//access myForm using document object
var name = document.name.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<div id="welcomeText">
<form onsubmit="changeText()" method="post" id="welcomeForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById("welcomeForm").fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="welcomeText">
Name: <input type="text" name="fname" id="name">
<input id="submit" type="submit" onclick="changeText()" onsubmit="changeText()">
</div>
<script>
function changeText() {
var name = document.getElementById("name").value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
document.getElementById("name").style.display = "none";
document.getElementById("submit").style.display = "none";
}
</script>
</body>
</html>
Try this it will display "welcome user" and also make button and input disappear. In this case you don't even need a form. You can access the name directly from the input without ever submitting the form.
Here we are:
<div id="welcomeText">
<form id="myform" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
var form = document.getElementById("myform");
form.addEventListener('submit', function (e) {
e.preventDefault(); // This will prevent submitting the form
var name = form.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
});
</script>

Categories