I'm trying to create 'customer' object that will store all of this data and then display the information as a ‘Customer Order' with listing all the new information. I guess it must be something like this.
var objectarray=[];
var customer={ name,address,postalcode,phone,email}
function addToArray() {
var customerobject={name,address,postalcode,phone,email};
customerobject.name=document.getElementById("name").value;
customerobject.address=document.getElementById("address").value;
customerobject.postalcode=document.getElementById("postalcode").value;
customerobject.phone=document.getElementById("phone").value;
customerobject.email=document.getElementById("email").value;
objectarray.push(customerobject);
displayList();
}
However, the main problem for me is that I can't figure out how to store all of this data and then display the information as a ‘Customer Order' with listing all the new information.
var customerobject={name,address,postalcode,phone,email};
isn't correct. Actually you're just giving your objects the keys without a value.
This is how it should look like:
var customerobject = {name: "",address: "",postalcode: "",phone: "",email: ""}
Here's an example based on your code:
var objectarray = [];
function addToArray() {
var customerobject = {
name: "",
address: "",
postalcode: "",
phone: "",
email: ""
}
customerobject.name = document.getElementById("name").value;
customerobject.address = document.getElementById("address").value;
customerobject.postalcode = document.getElementById("postalcode").value;
customerobject.phone = document.getElementById("phone").value;
customerobject.email = document.getElementById("email").value;
objectarray.push(customerobject);
console.log(objectarray);
}
document.getElementById("clickMe").addEventListener("click", clicked);
function clicked() {
addToArray();
}
<input id="name" value="Gregory" />
<input id="address" value="Mapstreet" />
<input id="postalcode" value="56467454" />
<input id="phone" value="1234" />
<input id="email" value="me#myself.com" />
<button id="clickMe">click me</button>
Related
I'm new to programming. Right now I'm trying to add a few strings that are given in a form in HTML to an array thats stored inside a Jscript. The relevant code:
<input type="text" id="fName" placeholder="Vorname" />
<input type="text" id="fNachname" placeholder="Nachname" />
<input type="email" id="fEmail" placeholder="E-Mail" />
<button id="formSubmit" > Absenden </button>
And here the jscript:
document.getElementById("formSubmit").addEventListener("click", Person);
function Person(vorname, name, email) {
this.name = name;
this.vorname = vorname;
this.email = email;
}
var Personen = [
new Person(document.getElementById("fName"), document.getElementById("fNachname"), document.getElementById("fEmail") )
]
document.getElementById("formSubmit").addEventListener("click", console.log(Personen));
But right now, it does not show in the console when I give the array a person. It simply gives me the code that is stored inside the Personen variable. How can I resolve this?
function Person(vorname, name, email) {
this.name = name;
this.vorname = vorname;
this.email = email;
}
var Personen = [];
var addPerson = function() {
Personen.push(new Person(document.getElementById("fName").value, document.getElementById("fNachname").value, document.getElementById("fEmail").value ));
console.log( Personen);
}
document.getElementById("formSubmit").addEventListener("click", addPerson);
<body class='home'>
<input type="text" id="fName" placeholder="Vorname" />
<input type="text" id="fNachname" placeholder="Nachname" />
<input type="email" id="fEmail" placeholder="E-Mail" />
<button id="formSubmit" > Absenden </button>
</body>
function Person(vorname, name, email) {
this.name = name;
this.vorname = vorname;
this.email = email;
}
var Personen = [];
var addPerson = function() {
Personen.push(new Person(document.getElementById("fName").value, document.getElementById("fNachname").value, document.getElementById("fEmail").value ));
console.log( Personen);
}
document.getElementById("formSubmit").addEventListener("click", addPerson);
this should add a person when you submit
You should do it in as an object and not as function
var Personen = new Array();
Personen.push({name : document.getElementById("fName"),vorname :document.getElementById("fNachname"),email : document.getElementById("fEmail") })
Gday
Im creating a javascript/typescript application that can create and edit contacts
currently stuck on the creating of the contact -- please view the code below. I have created a function called "createContact" that will validate the users input. Then pass the valid information to "addContact"
//mock data to fill array
let peter = {
firstName: "Peter",
lastName: "Best",
companyName: "Industrie Clothing",
phoneNumber: "0435 000 000",
email: "email#email.com",
postalAddress: "7 Myco Court"
};
//storing the mock data in an array
let contacts = [peter];
// sending to the console - troubleshooting
function printPerson(person):void {
let li = document.createElement("li");
let node = document.createTextNode(person.firstName+" "+person.lastName +" "+ person.phoneNumber);
li.appendChild(node);
let elt = document.getElementById("contactList");
elt.appendChild(li);
}
//this function is used to loop through ALL contacts
function list():void{
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}
// function to "add" a contact into the contacts array
function addContact(firstName: string, lastName: string, companyName: string, email: string, phoneNumber: string, postalAddress: string):void{
let object = {
firstName: firstName,
lastName: lastName,
companyName: companyName,
email: email,
phoneNumber: phoneNumber,
postalAddress: postalAddress
};
contacts[contacts.length] = object;
};
function createContact():void{
let firstName = <HTMLInputElement>document.getElementById("firstName");
let surname = <HTMLInputElement>document.getElementById("surname");
let phoneNumber = <HTMLInputElement>document.getElementById("phoneNumber");
let email = <HTMLInputElement>document.getElementById("email");
let companyName = <HTMLInputElement>document.getElementById("companyName");
let postalAddress = <HTMLInputElement>document.getElementById("postalAddress");
if((email.value == "") || (phoneNumber.value == "")){
alert("Please Provide Either An Email or Phone Number");
}
else {
alert("ALL GOOD");
addContact(firstName, surname, phoneNumber, companyName, email, postalAddress);
}
}
addContact("tim", "tom", "google", "timtom#example.com", "0436 139 648", "home is where the heart is");
//displaying contacts
list();
HTML
<div class="content">
<div id="createContact">
First name:<br>
<input type="text" id="firstName" name="firstName">
<br>
Last name:<br>
<input type="text" id="lastName" name="lastName" required>
<br>
Company Name:<br>
<input type="text" id="companyName" name="companyName">
<br>
Email:<br>
<input type="email" id="email" name="email">
<br>
Phone Number:<br>
<input type="text" id="phoneNumber" name="phoneNumber">
<br>
Postal Address:<br>
<input type="text" id="postalAddress" name="postalAddress">
<br><br>
<button onClick = "createContact()">Submit</button>
</div>
</div>
Let me know what my problem is!
Thank you
function createContact():void{
let firstName = <HTMLInputElement>document.getElementById("firstName");//HTML Element
let surname = <HTMLInputElement>document.getElementById("surname");
let phoneNumber = <HTMLInputElement>document.getElementById("phoneNumber");
let email = <HTMLInputElement>document.getElementById("email");
let companyName = <HTMLInputElement>document.getElementById("companyName");
let postalAddress = <HTMLInputElement>document.getElementById("postalAddress");
if((email.value == "") || (phoneNumber.value == "")){
alert("Please Provide Either An Email or Phone Number");
}
else {
alert("ALL GOOD");
addContact(firstName, surname, phoneNumber, companyName, email, postalAddress);//youre passing HTML Elements...
}
It looks like youre passing html Elements. Your function accepts strings, so you either do this:
addContact(firstName.value, surname.value, phoneNumber.value, companyName.value, email.value, postalAddress.value)
Or you make your code a bit shorter:
function createContact():void{
var values=["firstName","surname","phoneNumber","email","companyName","postalAdress"].map(el=>document.getElementById(el).value);
if(values[3]=="" || values[2]==""){
return alert("please provide Email and PhoneNumber");
}
addContact(...values);
}
Note: This is ES6, so you may use Babel etc. to use in real environments...
To refresh a div you can reset its contents:
function list():void{
document.getElementById("contactList").innerHTML="";//reset
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}
Now you just need to call that at the end of createContact...
I'm new to S.O and javascript. I am working on a final year project for a e-commerce website and have ran into a dead end on saving data from a form into local storage. My code is below, i really don't see where i have gone wrong. all help is appreciated.
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Populate the form fields
populateForm();
// Get the form
var form = document.getElementById("franchiseForm");
// Event listener for when the bookings form is submitted.
form.addEventListener("submit", function(e) {
saveData(form);
});
}
}
// Save the form data in LocalStorage.
function saveData() {
//fetch sava(data)
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//store the values
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
localStorage.setItem("address1", address1.value);
localStorage.setItem("address2", address2.value);
localStorage.setItem("city", city.value);
localStorage.setItem("pcode", pcode.value);
localStorage.setItem("phone", phone.value);
}
// Attempt to populate the form using data stored in LocalStorage.
function populateForm() {
// Fetch the input elements.
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//retrieve saved data and update the values of the form.
if (localStorage.getItem("fran_name") != null) {
name.value = localStorage.getItem("fran_name");
}
if (localStorage.getItem("name") != null) {
phone.value = localStorage.getItem("name");
}
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
}
window.onload = function(){
if (localstorage){
//populate the form fields
populateform(form);
}
}
<div id="section">
<form id="franchiseForm" action ="Order_confirmation.php" method="POST">
<div class="field">
<label for="fran_name">Franchise Name</label>
<input type="text" name="franchise_name" id="fran_name" placeholder="e.g One Delivery Leeds" pattern="[a-zA-Z]"
autofocus required tabindex="1">
<br>
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
<label for="address"> Address</label>
<input type="text" name="franc_address" id="address1" placeholder="Address Line 1" tanindex="3">
<input type="text" id="address2" placeholder="Address Line 2" tabindex="4">
<input type="text" id="city" placeholder="Town/City" tabindex="5">
<input type="text" id="pcode" placeholder="Postcode" tabindex="6">
<br>
<label for="phone" > Phone Number</label>
<input type="tel" name="franc_phone" id="phone" placeholder="Customer service number" min="10" maxlength="11" pattern="[0-9]{3}[-][0-9]{4}[-][0-9]{4}"
required title="Please provide your customer service number in the following format: 000-0000-0000" tabindex="7">
</div>
<div class="field">
<input type="submit" id="submit" value="submit">
</div>
</form>
The main thing is, check your console for this error:
Uncaught ReferenceError: localstorage is not defined.
Change your code. It is localStorage and not localstorage. That's a capital S.
And a big mistake here. It is getElementById and not getElemenyById:
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
You have too many mistakes! Elemeny != Element.
Looks like this is stopping your code from executing:
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
You don't have a variable named email. And moreover, you are trying to set the value of an undefined element variable email, which doesn't have a property named value, that prevents all your scripts from executing.
First of all, not in your code you use:
document.getElemenyById(...);
localstorage.setItem()
instead of (note the Elemeny vs. Element, s vs. S):
document.getElementById(...);
localStorage.setItem();
As for a full solution:
You can use various local storage to store this data in the browser.
You can do something like this when the page is about to reload:
window.onbeforeunload = function() {
var fran_name = document.getElementById("fran_name");
var name = document.getElementById("name");
// ...
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
// ...
}
localstorage works synchronously so this will work here.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
getItem will return null` if the data does not exist.
Use sessionStorage instead of localStorage if you want to store temporarily - until the browser is closed.
Here's a simplified version of your form, with complete working code. save it as a .html file:
<html>
<head>
<script type="text/javascript">
// For saving data:
window.onbeforeunload = function() {
var name = document.getElementById("name");
// ...
localStorage.setItem("name", name.value);
// ...
}
// For loading data:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
</script>
<title></title>
</head>
<body>
<div id="section">
<form id="franchiseForm" action="Order_confirmation.php" method="POST">
<div class="field">
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
</div>
</form>
</div>
</body>
</html>
If you are able to use JQuery and JQuery Cookie, you can save the data in a cookie:
var frn = $(#fran_name).val();
$.cookie("fran_name", frn);
Then on pageload you get the cookie data and then insert it into the field:
$(document).ready(function(){
var cookie = $.cookie("fran_name");
$('#fran_name').val(cookie);
});
I have a set of nesting json object like this:
var obj = {
name: "student",
contact: {
phone: "22222",
fax: "33333",
...
},
...
}
And I have these text fields:
<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
...
Now I want to fill these fields with appropriate property from above object. My question is how can I access anonymous property from that object?
For example suppose I have this jquery code:
$("#formID").find("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart = fieldName.split("_");
//I want something like this: console.log(obj.namePart[0].namePart[1])
});
Use obj["propertyName"]
obj[namePart[0]][namePart[1]]
$('#formID').find("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart;
if(fieldName.indexOf('_') > -1){
namePart = fieldName.split("_");
console.log(obj[namePart[0]][namePart[1]])
}
else{
namePart = fieldName;
console.log(obj[namePart])
}
});
*Note: The property is not anonymous. If your run obj["propertyName"] on an object with no such property it will return undefined.
<form ID="formID">
<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
</form>
$("#formID").find("input").each(function() {
fieldName = $(this).attr("name");
namePart = fieldName.split("_");
if(namePart.length ==1 && namePart[0]=="name"){
$(this).val(obj.name);
}
else if(namePart.length>1){
$(this).val(obj[namePart[0]][namePart[1]]);
}
//I want something like this: console.log(obj.namePart[0].namePart[1])
});
http://jsfiddle.net/57vL6b0w/
Edit: Sorry about that I misunderstood the question. What you are looking for is something like this.
var obj = {
name: "student",
contact: {
phone: "22222",
fax: "33333"
}
};
$('#formID').("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart = fieldName.split("_");
var arbitraryVal = obj;
for (var part in namePart) {
if (arbitraryVal.hasOwnProperty(namePart[part])) {
arbitraryVal = arbitraryVal[namePart[part]];
continue;
}
arbitraryVal = null;
break;
}
if (typeof $(this).val(arbitraryVal) !== 'undefined') {
$(this).val(arbitraryVal);
}
});
recusivly searches an object for each name part. If the name part is
contact_phone It will look for obj.contact.phone if it is something_else_with_lots_of_underscores it will look for obj.something.else.with.lots.of.underscores
JS FIDDLE
Lets say I have the following in C
struct address{
char name;
int id;
char address;
};
struct address adrs[40]; //Create arbitrary array of the structure. 40 is example
adrs[0].name = 'a';
id[0] = 1;
...
What is the equivalent way of defining and creating array of a user defined structure.
Thanks
If you're going to have a predefined layout for an object, you'd probably want to use a contructor-style function.
function address() {
this.name = null;
this.id = null;
this.address = null;
}
arrays are not typed and you don't have to specify a length.
var adrs = [];
you can create a new instance of address like so
var item = new address(); // note the "new" keyword here
item.name = 'a';
item.id = 1;
// etc...
then you can push the new item onto the array.
adrs.push(item);
alernatively you can add a new item from the array and then access it by indexer.
// adrs has no items
adrs.push( new address() );
// adrs now has 1 item
adrs[0].name = 'a';
// you can also reference length to get to the last item
adrs[ adrs.length-1 ].id = '1';
Equivalent would be creating an array of associative arrays.
var arr = new Array();
arr[0] = { name: "name 1", id: 100, address: "addr 01" };
arr[1] = { name: "name 2", id: 101, address: "addr 02" };
//...
After this, you will be able to do:
arr[0].name = "new name 1";
Or access element:
if (arr[1].name == "name 2") { // will be true
}
Hope it helps.
Answer is veryyyy Simple.
const address = {
name: ""
id: 1,
address: ""
}
Or Dynamic
const address = (name, id, address) => {
// Here your checks if enters is correct
return {name, id, address}
}
If You Use TypeScript? It's so simple to.
interface address {
name: string;
id: number;
address: string;
}
const adress: adress = {
.....
}
<script type="text/javascript">
function address()
{
this.name="";
this.id=0;
this.address=""
}
var addresses = new Array(40);
addresses[0] = new address();
addresses[1] = new address();
.....
.....
addresses[0].name = 'a';
addresses[1].id = 5;
</script>
A common problem that is solved by structure is ranking system. An array that contains name and number of some users and then sorting users according to number. Here is javascript implementation of this problem.Object array is used here
<!DOCTYPE html>
<html>
<head>
<title>Structure</title>
</head>
<body>
<label>Enter Student Name 1:</label>
<input type="text" id='n0' name=""><br>
<label>Enter Student Mark 1:</label>
<input type="text" id='m0' name=""><br>
<label>Enter Student Name 2:</label>
<input type="text" id='n1' name=""><br>
<label>Enter Student Mark 2:</label>
<input type="text" id='m1' name=""><br>
<label>Enter Student Name 3:</label>
<input type="text" id='n2' name=""><br>
<label>Enter Student Mark 3:</label>
<input type="text" id='m2' name=""><br>
<input type="button" value="Ranking" onclick="result()">
<div id='id'></div>
<script type="text/javascript">
function result()
{
var b=new Array(100);
var n1=document.getElementById('n0').value;
var m1=document.getElementById('m0').value;
var n2=document.getElementById('n1').value;
var m2=document.getElementById('m1').value;
var n3=document.getElementById('n2').value;
var m3=document.getElementById('m2').value;
var a=new Array(100);
var b=new Array(100);
var n,m,j,i,temp,t,r="<br>Ranking<br><br>";
for(i=0;i<3;i++)
{
n=document.getElementById('n'+i).value;
m=document.getElementById('m'+i).value;
m=parseInt(m);
a[i]={name:n,mark:m};
}
for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
if(a[j].mark>a[i].mark)
{
temp=a[i].mark;
t=a[i].name;
a[i].mark=a[j].mark;
a[i].name=a[j].name;
a[j].mark=temp;
a[j].name=t;
//console.log(a[i].name);
//console.log(a[i].mark);
}
}
}
for(i=0;i<3;i++)
{
r=r+a[i].name+" ";
r=r+a[i].mark+"<br>";
//console.log(a[i].name);
//console.log(a[i].mark);
}
document.getElementById('id').innerHTML=r;
}
</script>
</body>
</html>