Javascript onClick( ) function doesn't work [closed] - javascript

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">

Related

Displaying Associative array values using HTML elements

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"

adding style to items in an array

I am doing a madlibs-type program. Prompts ask for words, which are then added to a string. I would like the words used from the prompts to be underlined when they are displayed with the rest of the string. I have created an array with all the prompts. Now, I just need to know how to run through that array and change the text-decoration to "underline". I know I need to use a for-loop through the array, but not sure of how to approach it.
What is the best way to make this happen?
HTML:
<body>
<div id = "story-space">
</div>
<script src = "madlibs.js"></script>
</body>
JS:
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3, prompt4];
var text = "There was once was a " + prompt1 + " from " + prompt2 + " who liked to " + prompt3 + "."
document.getElementById("story-space").innerHTML = text;
Why can you add the html style like this
var text = "There was once was a <span style='text-decoration:underline'>" + prompt1 + "</span> from <span style='text-decoration:underline'>" + prompt2 + "</span> who liked to <span style='text-decoration:underline'>" + prompt3 + "</span>."
one simple way you can do it it as follows, note that you need to check for empty strings returned from prompt though, which is not handled in this answer,
var questions = ['an animal', 'a city', 'an activity'],
answers = [];
// create source string with placeholders that
// can be replaced with values in from prompts
var sourceText = "There was once was a {0} from {1} who liked to {2}."
//loop thru questions array and store answers in 'answers' variable
for (var q = 0; q < questions.length; q++) {
//create answer as span element
var question = questions[q],
answer = '<span style="text-decoration:underline;">';
answer += prompt('Enter ' + question);
answer +='</span>';
//update source text's 'qth' placeholder with answer
sourceText = sourceText.replace( new RegExp( "\\{" + q + "\\}", "g" ), function() {
return answer;
});
}
//update the target element's innerHTML
document.getElementById("story-space").innerHTML = sourceText;
You can try something like this by mapping all the prompts with an underline class.
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3];
prompts = prompts.map(prompt => `<span class="underline">${prompt}</span>`)
var text = "There was once was a " + prompts[0] + " from " + prompts[1] + " who liked to " + prompts[1] + "."
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>
You can also try something like below where you just provide the pre-text for your prompt and let the Map and Reduce do the rest of the job for you.
let textPromptMap = new Map();
textPromptMap.set("There was once was a ", prompt("Enter a animal."))
textPromptMap.set(" from ", prompt("Enter a city."))
textPromptMap.set(" who liked to ", prompt("Enter an activity."))
const text = [...textPromptMap.keys()]
.reduce((a, b) =>
`${a}${b}<span class="underline">${textPromptMap.get(b)}</span>`, ""
)
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>

Input to object

My question is: How to migrate var x which is basically user input data to var person so user could change person.firstName by inputing data into <input type="text" id="userInput" value=""> element. I am very new for JS concepts, so I would be appreciate for any help. Thank you.
var person = {
firstName : "John",
lastName : "Doe",
age : 30,
fullName : function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName (); // Result: My name is John Doe I am 30 yers old
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = x;}
You can add the event input to your input field.
Set the entered input (firstName) to your object person.
Look this code snippet:
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName();
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
person.firstName = x;
document.getElementById("demo").innerHTML = person.fullName();
}
document.getElementById("userInput").addEventListener('input', myFunction);
<span id='demo'></span>
<p>User Input</p>
<input type="text" id="userInput" value="">
See? The object person is being updated automatically.
Resource
EventTarget.addEventListener()
Working with objects
Just do what you say:
function updateFirstName() {
person.firstName = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = person.fullName();
}

How to format a text in a mailto function

I have two arrays and an object. One array conatins product codes, and another contains the quantities thereof. For example, the first quantity in the quantities array is the quantity of the product code that is the first one in the product code array. I also have an object that contains customer data. It would look something like this:
customer={
name:' firstname lastname',
email: 'example#domain.com',
company: "company name",
phone_number: 'phone number',
}
the arrays would look like this:
product_codes=[code_1; code_2; code_3];
quantities=[23, 56, 45];
Say that all of this is being mailed to customersupport#example.com.
I am familiar with the basics of the mailto function, but I would like to know if there is a way to format the body of the email so that it looks something like this:
...................................
Name: customer.name
email: customer.email
company name: customer.company
phone number: customer.phone_number
product code 1: corresponding quantity
product code 2: corresponding quantity
product code 3: corresponding quantity
...............................................
I would also like to be able to add any other given codes and quantities, as I am not sure of how many there will be. Is this even possible? If so, how? Please explain so that I can not only use it, but also understand how it works. Thanks!
If I'm not being clear enough, please let me know so I can edit it for greater clarity.
var sendEmail = function() {
var customer, body, quantities, product_codes;
customer = {
name: 'First Last',
email: 'example#example.com',
company: 'Company',
phone_number: 'phone number',
}
body = 'Name: '+ customer.name;
body += '\nEmail: '+ customer.email;
body += '\nCompany: '+ customer.company;
body += '\nPhone Number: '+ customer.phone_number;
product_codes = ['code_1', 'code_2', 'code_3'];
quantities = [23, 56, 45];
for(var i = 0; i < product_codes.length; i += 1) {
body += '\nProduct Code '+ product_codes[i] +': '+ quantities[i];
}
subject = 'Your Subject';
window.location = 'mailto:customersupport#example.com?body='+ encodeURIComponent(body) +'&subject='+ encodeURIComponent(subject);
};
// execute this function when the user clicks the #send-email button
var button = document.getElementById('send-email');
button.addEventListener('click', sendEmail);
I would build the string in a function:
HTML:
Click to Email
JAVASCRIPT:
//stuff you specified...
var customer={
name:' firstname lastname',
email: 'example#domain.com',
company: "company name",
phone_number: 'phone number',
}
var product_codes=['alpha', 'beta', 'gamma'];
var quantities=[23, 56, 45];
/* Assign a click action onto the link */
var yourLink = document.getElementById("thelink");
yourLink.onclick = function() {
var elf = "%0A"; //Encoded Line Feed
mailtoBody = "Name: " + customer.name + elf
+ "Email: " + customer.email + elf
+ "Company Name: " + customer.company + elf
+ "Phone Number: " + customer.phone_number + elf;
for (var i=0; i < product_codes.length; i++) {
mailtoBody += product_codes[i] + ": " + quantities[i] + elf;
}
location.href = "mailto:you#example.com?body=" + mailtoBody;
}
Here's a working example:
http://jsbin.com/kigutuhiqa/edit?html,js,output
It sounds to me like you want to construct the body of a message. If this is the case, you can create a function that builds the body of your message by taking in the 3 objects you mentioned: customer, codes, and quantity.
For example, you can do something like
function buildBody(cust, codes, quant){
var body = "";
body += "Name: " + cust.name + "\n";
body += "Email: " + cust.email + "\n";
body += "Company Name: " + cust.companyname + "\n";
for(var i=0; i<codes.length; ++i)
body += "Product Code " + codes[i] + ": " quant[i] + "\n";
return body;
}
I have not tested this code, but hopefully you get the idea.

JavaScript #media print stylesheet not working

I have started trying to make simple HTML and CSS webpages while incorporating a bit of JavaScript. I'm trying to make a simple print button that doesn't show up when you print it. I've searched around SA for various answers and I've seen a lot of things about the link media= "print". In the stylesheet would be a class where you would write either display: none or visibility: hidden. You would then apply that to your button.
The problem is that when I try doing it, it doesn't turn invisible when the page preview pops up. Here is my main code:
<link rel="stylesheet" href="print.css"
type="text/css" media="print" />
<script type = "text/javascript">
function newPerson(firstname, lastname, age, gender, birthmonth, birthdate) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.gender = gender;
this.birthmonth = birthmonth;
this.birthdate = birthdate;
this.birthyear = birthdayCalculate;
}
function birthdayCalculate() {
var date = new Date();
var CurYear = date.getFullYear()
var CurMonth = date.getMonth()
var birthyear = CurYear - this.age
if (this.birthmonth > CurMonth) {
birthyear --
}
return birthyear
}
function testFunction(form) {
var firstName = form.firstName.value
var lastName = form.lastName.value
var Age = form.Age.value
var Gender = form.Gender.value
var birthMonth = form.birthMonth.value
var birthDate = form.birthDate.value
var new1 = new newPerson(firstName, lastName, Age, Gender, birthMonth, birthDate)
var person = new1.firstname + " " + new1.lastname + " is " + new1.age + " and is " + new1.gender + " and was born on "
+ new1.birthmonth + "/" + new1.birthdate + "/" + new1.birthyear() + "." + "<br />"
document.write(person);
winVar = window.open();
winVar.document.write(person);
winVar.focus();
winVar.document.write(
"<input type='button' " +
"onClick= 'window.print();'" +
"value ='Print This Page' " +
"class = 'print' " +
"/>");}
</script>
I think you'd be able to tell I used forms. I don't think I need to show you this. The print .css is extremely simple too:
.print{
visibility: hidden
}
Does anyone see anything wrong with my script? A little something else, I'm using Google Chrome.
css will not help in this case use javascript instead. You have to do something like this:
assume this is your print button
<input type="button" value="print" onclick="this.setAttribute('hidden''hidden')"/>
hide the button when it clicked using the setAttribute function.
hope it will work..

Categories

Resources