I want to display the value of an associative array using html elements, but I can't seem to get the values because it always outputs undefine.
my code works like this : the user will register data, the registered data will be stored in an object and will be using a key "username" to access it. When a user search a username the values must be displayed using html elements.
here is my code. thank you
var storage = [];
function viewUserArray()
{
var zName = document.getElementById('checkArray').value;
var html = "<h1> Username Details </h1>";
var anotherhtml = "<p>";
var uName;
var fName;
var elmail;
var pword;
var b_day;
var g_nder;
for (key in storage)
{
if(key === zName)
{
uName = storage[key].uName;
fName = storage[key].fName;
elmail = storage[key].elmail;
pword = storage[key].pword;
b_day = storage[key].b_day;
g_nder = storage[key].g_nder;
html += "<p>Username : " + uName + "</p>";
html += "<p>Full Name : " + fName + "</p>";
html += "<p>Email : " + elmail + "</p>";
html += "<p>Password : " + pword + "</p>";
html += "<p>Age : " + b_day + "</p>";
html += "<p>Gender : " + g_nder + "</p>";
}
document.getElementById("target").innerHTML = html;
}
}
function setValuesArray()
{
var uName = document.getElementById('username').value;
var fName = document.getElementById('fullName').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = getAge();
var g_nder = document.getElementById('gender').value;
storage[uName] = (storage[uName]||[]).concat({//add user to storage[uName]
"Username" : uName,
"Full Name" : fName,
"Email" : elmail,
"Password" : pword,
"Age" : b_day,
"Gender" : g_nder
});
}
Pretty much same as other answer:
var storage = {};
function viewUserArray()
{
var zName = document.getElementById('checkArray').value;
var html = "<h1> Username Details </h1>";
var anotherhtml = "<p>";
var uName;
var fName;
var elmail;
var pword;
var b_day;
var g_nder;
if(!storage[zName]){
console.log("doesn't exist");
return;
}
uName = storage[zName].uName;
fName = storage[zName].fName;
elmail = storage[zName].elmail;
pword = storage[zName].pword;
b_day = storage[zName].b_day;
g_nder = storage[zName].g_nder;
html += "<p>Username : " + uName + "</p>";
html += "<p>Full Name : " + fName + "</p>";
html += "<p>Email : " + elmail + "</p>";
html += "<p>Password : " + pword + "</p>";
html += "<p>Age : " + b_day + "</p>";
html += "<p>Gender : " + g_nder + "</p>";
document.getElementById("target").innerHTML = html;
}
}
function setValuesArray()
{
var uName = document.getElementById('username').value;
var fName = document.getElementById('fullName').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = getAge();
var g_nder = document.getElementById('gender').value;
//I assume there is only one uName so update the uName if it exist and create it if it doesn't
// storage[uName] = (storage[uName]||[]).concat({//add user to storage[uName]
storage[uName] = {//update or add
uName,
fName,
elmail,
pword,
b_day,
g_nder
};
}
You also don't consistently get the values under the same keys that you save them in:
You save a user as: "Username" : uName, but then magically expect to get the value with: storage[zName].uName Saving a value under key "Username" but then try to get the value using a key "uName"
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I will be adding a list of contacts and put them in a div based on first character of lname. If the div doesn't exists, it will be created dynamically. I'd want to display the contact information on clicking the name. In the following implementation, showMe( ) function not working to display the contact information .
<html>
<head>
<style>
.holder{
background-color:yellow;
margin-top:10px;
width: 300px;
}
.holder span{
background-color: Green;
height:20px;
color:white;
}
</style>
<script>
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 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>"+lastNameFirstChar+"</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHTML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + currPerson.id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id) {
alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname+" "+person.lname+"</br> "+person.email+"</br>"+person.phone;
target.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
</head>
<body>
<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv">
</div>
</body>
</html>
<script>
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 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 id = contacts.length - 1;
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if (!document.getElementById(lastNameFirstChar + "_holder"))
{
document.getElementById("mydiv").innerHTML += "<div id='" + lastNameFirstChar + "_holder' class='holder'><span>" + lastNameFirstChar + "</span></br></div>";
}
//document.getElementById(lastNameFirstChar + "_holder").innerHML += currPerson.fname+" "+currPerson.lname + "<br/>";
document.getElementById(lastNameFirstChar + "_holder").innerHTML += "<span onclick='showMe(" + id + ")'>" + currPerson.fname + " " + currPerson.lname + "</span><br/>";
}
function showMe(id)
{
//alert(id);
var person = contacts[id]; /* currently corresponds to array index, could be a property lookup with underscore or whatever */
var contactInfo = person.fname + " " + person.lname + "</br> " + person.email + "</br>" + person.phone;
mydiv.innerHTML = "<div>" + contactInfo + "</div></br>";
}
</script>
When you call showMe() function you are supposed to send the id of the person by currPerson.id
but when you defined var person you didn't give it the id property.
you have this
var person = {
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
make it like this
var person = {
id: contacts.length,// note this extra parameter
fname: firstName,
lname: lastName,
email: emailId,
phone: phoneNo
};
now when you call
"<span onclick='showMe(" + currPerson.id + ")'>"
currentPerson.id will not be undefined anymore.
Secondly when you call this line
target.innerHTML = "<div>" + contactInfo + "</div></br>";
you haven't defined the variable "target".
add this line before the above line
var target= document.getElementById("mydiv")
where "myDiv" is the id of what you defined in the html markup
<div id="mydiv">
So i am learning Javascript and trying to set and retrieve a cookie, my code all looks to be ok but there is obviously a problem here.
function init()
{
var panel = document.getElementById("panel");
var user = escape("Dan, 000456");
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
When I look in the results they are not what I am expecting to see:
Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined
Your main issue is now that you have corrected your syntax errors is that the following line:
var user = escape("Dan, 000456");
note: I believe the escape function is now deprecated?
change your javascript to this and make sure your browser allows cookies:
function init(){
var panel = document.getElementById("panel");
var user = ["Dan, 000456"]; //<--change #1
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
//change #2 below added the array index of user to set the cookie value for myData
document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
Also make sure your html looks like this:
<div id="panel">Test</div>
You can remove the Test from the div in the html above if you want. The Test value should be replaced by values in your panel.innerHTML assignments.
Need some help with this piece of a code. I am able to produce the results I want with the code in Working Code, but when I implement this code on another sheet (which is the master code) it does not work. scratching my head trying to figure this out
Here is the shared google spreadsheet with both full codes. Go to script editor.
Google Docs Link
Any help would be much appreciated. Thank you in advanced.
EDIT#3 Submit section of None Working Code
function submit(e){
var app = UiApp.getActiveApplication();
var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var projectname = e.parameter.projectname;
var projectid = e.parameter.projectid;
var projectmanager = e.parameter.projectmanager;
var salesrep = e.parameter.salesrep;
var duedate = e.parameter.duedate;
var projectphase = e.parameter.projectphase;
var disctype = e.parameter.disctype;
var mediatype = e.parameter.mediatype;
var encryptiontype = e.parameter.encryptiontype;
var password = e.parameter.password;
var quantity = e.parameter.quantity;
var specialinstructions = e.parameter.specialinstructions;
var update = "Colombo Save";
//var sheet = ss.getSheets()[0];
var uiData = [[
projectname,
projectid,
projectmanager,
salesrep,
duedate,
projectphase,
disctype,
mediatype,
encryptiontype,
password,
quantity,
specialinstructions,
update
]];
sheet.getRange(sheet.getLastRow()+1, 1, uiData.length, uiData[0].length)
.setValues(uiData);
var app = UiApp.getActiveApplication();
var result = {};
var numMembers = parseInt(e.parameter.table_tag);
result.members = [];
for(var i=1; i<=numMembers; i++){
var member = {};
member.firstName = e.parameter['fName'+i];
member.lastName = e.parameter['lName'+i];
member.company = e.parameter['company'+i];
member.address = e.parameter['address'+i];
result.members.push(member);
}
var htmlBody = 'Shipping Information: <br>'
for(var a in result.members) {
var member = result.members[a];
var fname = member.firstName;
var lname = member.lastName;
var company = member.company;
var address = member.address;
var timestamp = Utilities.formatDate(new Date(), "America/New_York", "MMMM dd, yyyy hh:mm:ss"); // Timestamp
var activeSessionuser = Session.getActiveUser();//Session.getEffectiveUser(); Get the current user in the spreadsheet
var emailAddress = 'test#email.com'; //Venue Colombo Team
var subject = "**Test Email** DVD Request Submitted - **Test Email**"+ projectname +" - "+projectid+" - "+ projectmanager;
/^var emailBody =*/
var emailBody =
"<br><font color=\"Blue\"><b><h2>Request Submitted</h2></b></font>"
+"<br/>Hi Venue Colombo Team,<br/>"
+"<br/>The following data room(s) will need a disc creation. Please begin bulk save data room and create ISO to upload to the FTP site:<br/>"
+"<br/><b>Project Name:</b> " + projectname
+"<br/><b>Project ID:</b> " + projectid
+"<br/><b>Project Manager:</b> " + projectmanager
+"<br/><b>Sales:</b> " + salesrep
+"<br/>" + htmlBody + 'Client Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Address: ' + address +'<br>'+'<br>'+
+"<br/>"
+"<br/><b>Phase:</b> " + projectphase
+"<br/><b>Disc Type:</b> " + disctype
+"<br/>"
+"<br/><b>Encryption:</b> " + encryptiontype
+"<br/><b>Password:</b> " + password
+"<br/><b>Quantity:</b> " + quantity
+"<br/>"
+"<br/><b>Client Due Date:</b> " + duedate
+"<br/>"
+"<br/><font color=\"Red\"><b>Special Instructions:</b></font> " + "<br/>"+ specialinstructions
+"<i><br/> <br/>This request was submitted by:</i> "
+"<br/><font color=\"blue\">Name:</font> " + activeSessionuser
+"<br/>Time Stamp: " + timestamp
+"<br/>"
+"———————————————————————————————"
+ //Line divider code —
"<br/>Venue Client Services"
+"<br/>United States: "
+"<br/>UK/International: "
+"<br/>France: "
+"<br/>Asia: ";
htmlBody += 'Client Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Address: ' + address +'<br>'+'<br>';
}
var optAdvancedArgs = {name: "Venue Client Services", htmlBody: emailBody};
//MailApp.sendEmail('fake#email.com', subject, '', optAdvancedArgs);
Logger.log(htmlBody);
Logger.log(emailBody);
var html = app.createHTML('First Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Client Address: ' + address);
app.add(html);
//dvdForm();
return app;
}
Here is the result on the Application
Here is the Logger logs
Logger.log(htmlBody);
Logger.log(emailBody);
I was finally able to figure out what the issues was with "for loop statement return undefined values"
I did not add a .addCallbackElement to the panel containing the form fields.
I'm new to JavaScript and I am trying to extract information from a query string on the web I created, if I load straight on the page without the query string the page will load but once I redirect from my form page to the page where I'm doing the parsing it freezes and crashes... can anyone help please! :(
http://main.xfiddle.com/7d679c3a/Project1/Commission.php
http://main.xfiddle.com/7d679c3a/Project1/contactForm.php
http://main.xfiddle.com/7d679c3a/Project1/DiceRoll.php
http://main.xfiddle.com/7d679c3a/Project1/IsEven.php
http://main.xfiddle.com/7d679c3a/Project1/palindrome.php
http://main.xfiddle.com/7d679c3a/Project1/part1.php
http://main.xfiddle.com/7d679c3a/Project1/passwordStrength.php
http://main.xfiddle.com/7d679c3a/Project1/allinOne.php
JavaScript Code
var $ = function(id)
{
return document.getElementById(id);
}
var formInfo = location.search();
formInfo = formInfo.substring(1, formInfo.length);
while (formInfo.indexOf("+") != -1)
{
formInfo = formInfo.replace("+", " ");
}
while (formInfo.indexOf("=") != -1)
{
formInfo.replace("=", " ");
}
formInfo = decodeURI(formInfo);
formInfo.replace("firstname", "");
formInfo.replace("lastname", "");
formInfo.replace("phonenumber", "");
formInfo.replace("postalcode", "");
formInfo.replace("startingmoney", "");
var infoArray = formInfo.split("&");
var firstName = infoArray[0];
var lastName = infoArray[1];
var phoneNumber = infoArray[2];
var postalCode = infoArray[3];
var startingMoney = infoArray[4];
$("playername").innerHTML = firstName + " " +lastName;
$("playerinfo").innerHTML = phoneNumber + " " + postalCode;
$("money").innerHTML = " $$" + startingMoney;
HTML Code
<div id="fireinfo">
<p id="playername"></p><br/>
<p id="playerinfo"></p>
<p id="money"></p>
</div>
I want to out put the information i get from the query string into the player name, player info and money id's.
Use this function to get query string value:
function getQueryString(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(window.location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
var firstname = getQueryString('firstname');
I get data from XML. I need to check data and if data is null I must hide this.
How can I check?
<script>
downloadUrl("gxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var oid = markers[i].getAttribute("objectid");
var status = markers[i].getAttribute("status");
var title = markers[i].getAttribute("title");
var volume = markers[i].getAttribute("volume");
var kwh = markers[i].getAttribute("kwh");
var puser = markers[i].getAttribute("puser");
var ucomp = markers[i].getAttribute("ucomplate");
var udate = markers[i].getAttribute("udate");
var suser = markers[i].getAttribute("suser");
var scomp = markers[i].getAttribute("scomplate");
var sdate = markers[i].getAttribute("sdate");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "ObjectID:" + oid + " <br/> Title:" + title +" <br/>Status:" + status + " <br/>Volume:" + volume + " <br/> KWh:" + kwh + " <br/>User:" + puser + " <br/> User Date:" + udate + " <br/> User Complate :" + ucomp + " <br/>Super user:" + suser + " <br/> S .User Date:" + sdate + " <br/> S. User Complate :" + scomp + "<br/> Add/Edit";
</script>
// this data i get from xml. i`m need to chek this null or not null
You can simply do a if (!myVariable) check on any given variable. If that returns true (that is to say if the code enters the if body, then the data is null. What I would do is instead of doing this:
var oid = markers[i].getAttribute("objectid");
// ...
..."ObjectID:" + oid + "
Include your title in the variable, like this:
var oid = markers[i].getAttribute("objectid");
if (oid) {
oid = "ObjectID: " + oid;
}
and that way you can add oid directly to your string. If the value is null, adding it will have no effect because the variable will be empty. If there was a value, then the title will be appended and doing a + oid will append the title and value at the same time.
if ( !foo ) {
// foo is not set, it is null.
}