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...
Related
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>
I am working with Parse for Javascript, and below is my dilema:
During the signup process, along with the username, and password, the first and last name of the user would have to recorded into parse. As of now, only the username and password is stored.
Below is the javascript signup function code:
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function(user) {
user.set("first_name", first_name);
user.set("last_name", last_name);
new ManageTodosView();
self.undelegateEvents();
delete self;
},
Below is the html form code (ask user to enter their information):
<form class="signup-form">
<h2>Sign Up</h2>
<div class="error" style="display:none"></div>
<input type="text" id="fname" placeholder="Please enter your First Name" />
<input type="text" id="lname" placeholder="Please enter your Last Name" />
<input type="email" id="signup-username" placeholder="Please enter your email" />
<input type="password" id="signup-password" placeholder="Create a Password" />
<button>Sign Up</button>
</form>
Any help would be greatly appreciated.
User.set won't save the changes you will need to call save once you set the first name and last name. Also you don't need to do this after calling signing up. Try the code below it should work.
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
var user = new Parse.User();
user.set("username", username);
user.set("password", password);
user.set("first_name", first_name);
user.set("last_name", last_name);
user.signUp(null, {
success: function(user) {
new ManageTodosView();
self.undelegateEvents();
delete self;
}
}
I am trying to create a very very basic profile page using Name, Email, Username, and Password. I have to have a password validation code/button.
The home page will be very similar to a common profile page. The user must be able to input the following:
Name field
Email field
User ID field
Password field 3
Validation Password field
The following buttons are required:
Password validation button
Create Profile button
I can put it all together, but the problem I am having is that the javascript console is telling me that there are some errors in the code...
function validate(){
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('Password2');
if (pass1 == pass2)
{
alert("Passwords Match")
}
else
{
alert("Passwords Do Not Match")
}
}
<head>
<script type="text/javascript" src="Profile Page.js"></script>
</head>
<body>
Enter First and Last Name
<input type="text" id="name">
<br>Enter Your Email Address
<input type="text" id="email">
<br>Please Enter a Username
<input type="text" id="username">
<br>Please Enter a Password
<input type="password" id="password">
<br>Enter Your Password Again
<input type="Password" id="password2">
<br>
<button type="button" id="validate" onClick="validate()">Validate Password</button>
<button type="button" id="create" onClick="submit()">Create Profile</button>
</body>
Ok, so I figured out where my errors were, now the alert that I set up for the passwords not matching is coming up, even when the passwords are the same thing. Any suggestions?
Please try it like this:
function validateForm(){
var pass1 = document.getElementsByName("password")[0].value;
var pass2 = document.getElementsByName("password2")[0].value;
if (pass1 === pass2) {
alert("Passwords Match");
} else {
alert("Passwords Do Not Match");
}
}
Enter First and Last Name
<input type = "text" id = "name" /><br/>
Enter Your Email Address
<input type = "text" id = "email" /><br/>
Please Enter a Username
<input type = "text" id = "username" /><br/>
Please Enter a Password
<input type = "password" name = "password" /><br/>
Enter Your Password Again
<input type = "Password" name= "password2" /><br/>
<button type = "button" id = "validate" onclick = "validateForm();">Validate Password</button>
<button type = "button" id = "create" onclick = "submit()">Create Profile</button>
Below is the generic function to validate password by comparing with repeat password, Contains lowercase, Contains uppercase, Contains digit
function validatePassword(password, repeatPassword){
var MinLength = 6;
var MaxLength = 15;
var meetsLengthRequirements:boolean = password.length >= MinLength && repeatPassword.length <= MaxLength;
var hasUpperCasevarter:boolean = false;
var hasLowerCasevarter:boolean = false;
var hasDecimalDigit:boolean = false;
if (meetsLengthRequirements)
{
for (var i = 0, len = password.length; i < len; i++) {
var char = password.charAt(i);
if (!isNaN( +char * 1)){
hasDecimalDigit = true;
}
else{
if (char == char.toUpperCase()) {
hasUpperCasevarter = true;
}
if (char == char.toLowerCase()){
hasLowerCasevarter = true;
}
}
}
}
var isValid = meetsLengthRequirements
&& hasUpperCasevarter
&& hasLowerCasevarter
&& hasDecimalDigit;
return isValid;
}
I have a login form that, when completed, sends users to a page with a JavaScript generated URL (allowing me to pass a JavaScript variable to my PHP script using $_GET). However, in order to do that, the Login button is currently 'type="button"'. While everything works, it means that users cannot login by hitting Enter; they must actually click the Login button. Is there a way I can "Submit" the form, while still having it point to the JavaScript generated URL?
This seems like a pretty basic concept, which tells me I might be approaching it the wrong way to begin with. Any guidance is appreciated.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
</form>
JavaScript:
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
window.open("home.php?display_name=" + displayName, "_self");
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
Instead of opening php page via javascript, you need to change the form action dynamically to point to your generated url.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" onclick="check(this.form)" value="Login"/>
</form>
JavaScript: (line 9 & 10 changed)
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
form.action = "home.php?display_name=" + displayName;
return true;
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
You could try:
<form name="login" onsubmit="check(this)">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" value="Login"/>
</form>
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>