Display array elements in html page as they are being entered - javascript

var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
for(i=0;i<contacts.length;i++){
document.getElementById("mydiv").innerHTML += contacts[i].fname+" "+contacts[i].lname;
}
}
I want to display only the new array elements. In the above code, every time a new element enters the array all elements are displayed. How can I avoid repetition? I think using the DOM is an option. I'm stuck trying to implement this.

You can do it like this, adding only the last element of array to innerHTML
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}

Before you add all the elements you have to empty your div.
document.getElementById("mydiv").innerHTML = ''

Here is a working snippet of what you asked. you just have to take the last pushed object from the array and display the names.
Also your var fname, lname, email, phone is not required, You can set the object properties on the fly.
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
// var fname, lname, email, phone; //also this is not required. you can set dynamic property names in a object.
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length-1]; //take the last pushed object from the array
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if(!document.getElementById(lastNameFirstChar + "_holder")){
document.getElementById("mydiv").innerHTML += "<div id='"+lastNameFirstChar+"_holder' class='holder'><span class='charValue'>"+lastNameFirstChar+"</span></br></div>";
}
document.getElementById(lastNameFirstChar + "_holder").innerHTML += currPerson.fname+" "+currPerson.lname + "<br/>";
}
<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv">
</div>
EDIT: Since you said you can use Jquery I have updated the solution with Jquery.

just change:
if(contacts.length!=0){
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}
The if check is for the start when length of array is zero

Related

Exception: The parameters don't match the method signature for ContactsApp.createContact

I want to create an automated process to convert google forms spreadsheet customer data to google contacts. I am not sure which string is it referring to that does not match the signature for ContactsApp.createContact.
I get an error saying:
Exception: The parameters (String,String,String,String) don't match the method signature for ContactsApp.createContact.
addContact # Google Contacts.gs:114
When I tried to implement a trigger upon completion of the form to automatically add the contacts in google contacts, it only shows the First Name, Last Name, Email, BUT NOT THE PHONE.
Section of code that has error
function addContact()
{
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getActiveCell();
var active_row = cell.getRow();
var range = sheet.getDataRange();
var first_name = range.getCell(active_row ,1).getValue();
var last_name = range.getCell(active_row ,2).getValue();
var email = range.getCell(active_row,3).getValue();
var phone = range.getCell(active_row,4).getValue();
var contact = ContactsApp.createContact(first_name, last_name, email, phone); (LINE 114)
var mainGroup = ContactsApp.getContactGroup("System Group: My Contacts");
mainGroup.addContact(contact);
showOutputBox('first name' + first_name + '\nlast name' + last_name + '\nemail' + email + '\nphone' + phone, "added contact");
}
This is the full code
// Add a menu
// Adds a menu item Contacts → add Contact
// Add a handler to handle when you click on that menu item.
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Contacts')
.addItem('add Contact', 'addContact')
.addToUi();
}
function formSubmitted(e){
addContact(e.namedValues);
}
// Add a contact from the Google sheet
// Picks up the contact from the currently selected cell.
// Google Sheet, first column First name, second column last name and third column email.
// Pick the values and call ContactsApp.createContact()
function addContact()
{
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getActiveCell();
var active_row = cell.getRow();
var range = sheet.getDataRange();
var first_name = range.getCell(active_row ,1).getValue();
var last_name = range.getCell(active_row ,2).getValue();
var email = range.getCell(active_row,3).getValue();
var phone = range.getCell(active_row,4).getValue();
var contact = ContactsApp.createContact(first_name, last_name, email, phone);
showOutputBox('first name' + first_name + '\nlast name' + last_name + '\nemail' + email + '\nphone' + phone, "added contact");
}
function showOutputBox(str, title)
{
var html = HtmlService.createHtmlOutput('<pre>'+str+'</pre>')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi()
.showModalDialog(html, title);
}
// Where is the new contact?
// If you open contacts.google.com you still will not see the new contact yet. There was no error too. So where did the new contact disappear?
// The reason is that the new contact is not a member of any of your contact groups. There are predefined groups called “system groups” in every account.
// Let us first add a function to list all the groups.
function showContactGroups()
{
var groups = ContactsApp.getContactGroups();
var str ='Groups\n';
for(var g = 0; g < groups.length; g++)
{
str +='\n'+groups[g].getName()
}
showOutputBox(str,'Your Contact Groups');
}
// Add a menu item to show the contact groups:
// Now your Contacts menu should have tow items. Select Contacts → show Groups.
// Show all the contact groups in your account
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Contacts')
.addItem('show Groups', 'showContactGroups')
.addItem('add Contact', 'addContact')
.addToUi();
}
// Let us add your new contacts to “My Contacts” group.
// Updated code:
function addContact()
{
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getActiveCell();
var active_row = cell.getRow();
var range = sheet.getDataRange();
var first_name = range.getCell(active_row ,1).getValue();
var last_name = range.getCell(active_row ,2).getValue();
var email = range.getCell(active_row,3).getValue();
var phone = range.getCell(active_row,4).getValue();
var contact = ContactsApp.createContact(first_name, last_name, email, phone);
var mainGroup = ContactsApp.getContactGroup("System Group: My Contacts");
mainGroup.addContact(contact);
showOutputBox('first name' + first_name + '\nlast name' + last_name + '\nemail' + email + '\nphone' + phone, "added contact");
}
Issue:
ContactsApp.createContact only accepts three parameters: givenName, familyName and email. There's no createContact method that accepts four parameters. Hence the error you are getting.
Solution:
Enable the Advanced People Service in order to use People API and create your contact via people.createContact, which allows you to set the contact's phone number (as well as a bunch of other properties).
Code sample:
const optionalArgs = {
personFields: "emailAddresses,names,phoneNumbers"
};
const resource = {
"emailAddresses": [
{
"value": email
}
],
"names": [
{
"givenName": first_name,
"familyName": last_name
}
],
"phoneNumbers": [
{
"value": phone
}
]
};
People.People.createContact(resource, optionalArgs);

Multiple user form input stored in an associative array using javascript

I can't seem to make another user input values into the array. Everytime that I want to add a new form value into the array it just overrides the data. is there any other way for this code to work? without using js libraries and frameworks.
Here is my code. Thank you.
function array()
{
var fName = document.getElementById('fullName').value;
var userName = document.getElementById('username').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = document.getElementById('bday').value;
var g_nder = document.getElementById('gender').value;
var storage = [];
var person = [];
person[userName] = {
"Full Name" : fName,
"Email" : elmail,
"Password" : pword,
"Birthday" : b_day,
"Gender" : g_nder
};
storage.push(person);
console.log(storage);
}
Keep storage outside the function as global variable.
var storage = [];
function array()
{
var fName = document.getElementById('fullName').value;
var userName = document.getElementById('username').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = document.getElementById('bday').value;
var g_nder = document.getElementById('gender').value;
var person = [];
person[userName] = {
"Full Name" : fName,
"Email" : elmail,
"Password" : pword,
"Birthday" : b_day,
"Gender" : g_nder
};
storage.push(person);
console.log(storage);
}
You are initilaizing storage to empty array every time

Converting Javascript array objects to uppercase

var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
}
How do I convert contacts array to uppercase? After converting the array to uppercase, I want to display the full name in alphabetical order as shown in the picture. Or is there any other way to accomplish without converting to uppercase?
You can use this to convert a string to title casing:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
See example usage:
var nameMixedCaseing = ["alan bong" , "JusTin weasel", "Tom curry"]
for (i = 0; i < nameMixedCaseing.length; i++)
console.log(toTitleCase(nameMixedCaseing[i]));
Result is:
Alan Bong
Justin Weasel
Tom Curry
So in your code you can call this function before saving the person object
person.firstName = toTitleCase(person.firstName);
person.lastName = toTitleCase(person.lastName);
contacts.push(person);
You can use a combination of functions, one to capitalize, one to sort each time a new contact is pushed into the array:
var contacts = [
{
fname: 'andrew',
lname: 'mCGonahan'
},
{
fname: 'paUla',
lname: 'Ptrokva'
},
{
fname: 'kevin',
lname: 'harGRove'
},
{
fname: 'CAmille',
lname: 'dUpoIs'
},
{
fname: 'AlbERt',
lname: 'sWanson'
}
];
function capitalize(arr) {
for (var i = 0; i < arr.length; i++) {
var first = arr[i].fname;
var last = arr[i].lname;
arr[i].fname = first.slice(0,1).toUpperCase() + first.slice(1).toLowerCase();
arr[i].lname = last.slice(0,1).toUpperCase() +last.slice(1).toLowerCase();
}
return arr;
}
function sortByLast(arr) {
return arr.sort(function(a, b) {
if (a.lname > b.lname) return 1;
if (b.lname > a.lname) return -1;
return 0;
});
}
//you can call the following after you have pushed the newest contact into the array
// or you could capitalize the inputs as they are entered, then run the sort function on the contacts array
contacts = sortByLast(capitalize(contacts));
document.getElementById('sortedContacts').innerHTML = JSON.stringify(contacts);
<div id="sortedContacts"><h3></h3></div>

validate a user registration form

I have a user registration form. I already use validation to check if all fields are filled. I need to validate email and mobile number using javascript and alert using an alertbox if its not valid. Please help
the code is
var name = $("#name").val();
var inst = $("#inst").val();
var email = $("#email").val();
var mobile = $("#mobile").val();
var dataString = 'name='+ name + '&inst='+ inst + '&email='+ email +'&mobile='+ mobile;
if(name==''|| inst=='' || email=='' || mobile=='')
{
alert("Please Enter all the Fields");
}
else
{ //rest of code comes here
var emailRe = /^\w+([\.\-]?\w+)*#\w+([\.\-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/;
var phoneRe = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var email_address = $('#email').val();
var phone_number = $('#phone').val();
if(emailRe.test(email_address) === false){
alert(email_address + ' is invalid');
}
if(phoneRe.test(phone_number) === false){
alert(phone_number + ' is invalid');
}
Reference: Regular Expressions Field Validation

javascript regex, split user's full name

I have user's firstname and lastname in one string, with space between
e.g.
John Doe
Peter Smithon
And now I want convert this string to two string - firstname and lastname
John Doe -> first = John, last = Doe
John -> first = John, last = ""
[space]Doe -> first = "", last = Doe.
I am using next code
var fullname = "john Doe"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // Doe
and this works well for two-word fullname. But if fullname has one word, then I have problem
var fullname = "john"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // john
http://jsfiddle.net/YyCKx/
any ideas?
Use split + shift methods.
var parts = "Thomas Mann".split(" "),
first = parts.shift(),
last = parts.shift() || "";
So in case of single word name it will give you expected result:
last = "";
Use this code:
You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.
function splitFullName(a,b,c){
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
document.getElementById(c).oninput=function(){
fullName = document.getElementById(c).value;
if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
first = fullName.capitalize();;
last = "null";
}else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
last = fullName.substring(first.length +1,fullName.length).capitalize();
}else{
first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
}
document.getElementById(a).value = first;
document.getElementById(b).value = last;
};
//Initial Values
if(document.getElementById(c).value.length === 0){
first = document.getElementById(a).value.capitalize();
last = document.getElementById(b).value.capitalize();
fullName = first + " " + last ;
console.log(fullName);
document.getElementById(c).value = fullName;}}
//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");
Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
You can use split method
var string = "ad";
var arr = string.split(" ");
var last = arr[0];
var first = arr[1];
if(first == null){
first = "";
}
alert(last + "\n" + first)​;​
If in every situation you have just "first last" you could use:
var string = "john "
var i = string.split(" ");
alert("first: "+i[0]+ "\n"+ "last: " + i[1]);
I know that this has already been replied to and marked as answered but i just want to note that if you do still want to use regex you can change the "last" expression:
var last = string.replace(/^[a-zA-Z]*/, "").toUpperCase().trim();
jQuery( window ).load(function() {
jQuery("#FullNametest").change(function(){
var temp = jQuery(this).val();
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++)
{
middlename = middlename +" "+ fullname[i];
}
jQuery('#FirstName').val(firstname);
jQuery('#LastName').val(lastname);
});
});
var str='John';
var str2='Peter Smithon';
var str3='Peter';
var words=str.split(/\s+/g,2);
var first=words[0];
var last=words[1]||'';
alert(first+' '+last);

Categories