basic function within object return - javascript

I'm sure I am missing something really basic here, but its had me stuck for about an hour and I can't seem to fix the problem.
Basically, I'm attempting to create a method within an object that will check against a checkbox value in html, and if true display three values within the same object to the console (and eventually I'll write this to the innerHTML of my form).
The following code simply writes "function()" to my console in firebug. Obviously, I'm trying to write firstName lastName email. What simple thing am I missing here? Thanks in advance!
function process() {
'use strict';
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var permission = document.getElementById("permission").checked;
var contactInfo = {
firstName: firstName,
lastName: lastName,
email: email,
permission: permission,
display: function() {
var contactCard;
if (this.permission == true) {
contactCard = firstName + " " + lastName + "<br />" + email
} else {
contactCard = "Permission Denied."
}
return contactCard;
}
};
console.log(contactInfo.display);
return false;
};
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
};
window.onload = init;

console.log(contactInfo.display());
You need to call the function.
You currently just have console.log(contactInfo.display); display is a function and is not being executed (so console will actually print the result of contactInfo.display.toString()), that is why you see 'function' and not the return value 'contactCard'.

Related

Not able to change value of Global var from inside function

I tried using this solution but it didn't work for me. In my case I am trying to save a variable using 1 function and call it from another
var postalcode = "code didn't change";
export function save_postal_code(code) {
var localcode = code
let postalcode = localcode;
console.log(code);
}
export function get_postal_code() {
console.log(postalcode);
return postalcode;
}
The save_postal_code function logs the correct value, but the get_postal_code function doesn't. I don't know what I am doing wrong.
You're redeclaring postalcode inside save_postal_code() instead of updating its value.
The code needs further revision, but that's outside the scope of this answer.
To have postalcode updated inside save_postal_code(), try:
var postalcode = "code didn't change";
function save_postal_code(code) {
let localcode = code
postalcode = localcode;
}
function get_postal_code() {
return postalcode;
}
save_postal_code("123")
console.log(get_postal_code())
This happens because you're instantiating the variable again using the let keyword (making a more immediate local variable with the same name)
removing the let keyword should fix your issue
var postalcode = "code didn't change";
export function save_postal_code(code) {
var localcode = code
postalcode = localcode;
console.log(code);
}
export function get_postal_code() {
console.log(postalcode);
return postalcode;
}

Update var using .change?

I have an important question that I'm starting to face on 80% of the cases.
Lets say I have this:
var bcount = properties.count;
favicon.badge(bcount);
bcount.change(function() { favicon.badge(bcount); });
properties.count = its a number that changes depending on the user actions.
favicon.badge its a javascript that shows the action, which is working good.
I tried to use .change on the bcount var, but is giving me error as I supposed because is not an element.
Is there any way to listen a var when value changes?
The problem I'm facing is that when the count gets updated, with a new number. It only updates after refreshing the page.
Thanks!!
Edit: I'm trying to setup getter and stter:
var bcount = {
a: properties.count,
get b() {
return this.a;
},
set c(cname) {
this.a;
}
};
Is that okay? And now how i can init the call?
I think you need get and set functionality. You can put logic in those functions and they will do what you want in variable get and set.
See this: es5-getters-setter
Sample from above link:
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin
Edit:
Every field has its get and set. If you want to make other confused when they read your code do that. but the right thing is this:
var properties = {
_count:0, // you hold count value here
get count() { // every time you get "properties.count" this function will run
// place for your code that must run on get, like "var bcount = properties.count"
return this._count;
},
set count(new_count) { // every time you want to do "properties.count = some_int" this function will run
// place for your code that must run on set, like "properties.count = some_int"
this._count = new_count;
}
};
// usage
properties.count = 10; // "properties._count" is "10" now
var bcount = properties.count; // you just got "properties._count" value

Javascript writing over previous value?

I'm very new to javascript, and can't figure this seemingly simple issue. I have an array of elements (say usernames) that i iterate over. i want to map these usernames to click event methods (i know this isn't the perfect way, but it's just something that seems to work):
this.events = this.events || {};
var self = this;
for (var i=0; i<arr.length; i++) {
console.log(data.user[i]); // < --- this username is correct
var username = data.user[i];
$(this.el).append("<td><button class='btn btn-primary save" + i + " btn-sm'>Save</button></td>");
var eventKeySave = 'click ' + '.save' + i;
this.events[eventKeySave] = function(){
(function (username) {
console.log("inside method save " + username); // <--- this username is wrong
self.onSave(username, 'something')
})(username);
};
}
this.delegateEvents();
now, in my onSave method, it just merely prints the usernames:
onSave: function(name, extras) {
console.log("you clicked save on " + name + " , " + type); // < -- wrong name
}
But why do i ALWAYS get only the LAST username of the array in my onSave function?
for example, if my array looks like [ 'david', 'emily', 'stephanie', 'michelle'], only michelle gets passed in to the onSave function, despite the fact that each button's click event should have been set with the respective name in the array.
i even tried to pass the username by value but it still doesn't work. what is going on in Javascript that i'm not seeing?
You need a closure:
this.events[eventKeySave] = (function (name) {
return function(){
console.log("inside method save " + name); // <--- this username is now ok
self.onSave(name, 'something');
};
})(username);
It happens because the function is called after that the for loop ended, so the value of "username" is the last value of the array in all cases.
Add a closure save the actual value of 'username' for that returned function

Is it possible to assign a value from local function to a global variable in javascript

Hey guys I have declared a global variable in my javascript file.Then iam assigning a value to the global variable in a local function.Then when iam trying to access the value of that global variable in other function,damn alert box is showing 'undefined'.Is there any way to access the value of a local variable in other function.I don't want to call the function from another function and send parameters with it.I just want to access the local variable of one function into some another function.
Hope someone takes me out of this.
Thank you guys and girls.
the code
var user_glob;
var pass_glob;
function osmlogin() {
var user = document.getElementById('uname').value;
var passw = document.getElementById('pwd').value;
user_glob = user;
pass_glob = passw;
if (user == '') {
document.getElementById('wrong_pwd').innerHTML = 'Please give your email_id';
}
else if (passw == '') {
document.getElementById('wrong_pwd').innerHTML = 'Please give your password';
}
else {
var data =
{
username: user,
pass: passw
};
$.getJSON('some url?jsonp=?', data, function (data) {
check = JSON.stringify(data['key1']);
if (check == 1 && user != '' && passw != '') {
window.location.href = "#page-dashboard";
}
else {
// alert(check);
document.getElementById('wrong_pwd').innerHTML = 'Wrong Username or Password';
}
});
}
}
now I want to use that global variable in this function
function announcement_view()
{
var user =user_glob;
var passw = passw_glob;
var data = {
username: user,
pass:passw
};
$.getJSON('some url?jsonp=?', data, function (data) {
var check = JSON.stringify(data['key1']);
alert(JSON.stringify(data['key1']));
alert(JSON.stringify(data['key2']));
if (check == 0 && user == '' && passw == '')
{
//alert(user_glob);
window.location.href = "#page-home";
}
});
}
If your code is something like this...
var a;
function f1(){
a= 1;
}
function f2(){
alert(a);
}
f1();
f2();
It should work fine.
Make sure you are calling the function that assigns the value (f1 in this case) before the function that alerts it (f2 in this case).

Javascript-Returning a value from a prompt

For instance, if we have:
var greeting = "What is your name?";
var userName = prompt(greeting);
How would I take the string input from the user to pass along into a procedure? Just as a for instance, we will assume we're telling a story through the console. How would I take that STRING data from the user and pass it along into a function immediately following that?
Yes, I know it's remedial, but I am trying to get a grasp on core concepts.
var greeting = "What is your name?";
function getUserName() {
return prompt(greeting);
}
function yourFunction() {
alert("Hello "+getUserName());
}
yourFunction();
Example of how to use the prompt value:
var greeting = "What is your name?";
var userName = prompt(greeting);
if(testUserName(userName))
{
alert('name is abc');
}
else
{
alert('name isnt abc');
}
function testUserName(userName)
{
return userName == 'abc';
}
JSFiddle
The userName variable is defined at run time as the return value of the prompt and can be passed as a function parameter to be used when the JavaScript is parsed. This is true of almost all returned values and its not just limited to strings.
Example: http://jsfiddle.net/bradlilley/nGLTf/
var userName = prompt("What is your name?");
function foo(bar) {
if (bar && bar.length) {
console.log(bar);
return;
}
console.log('The prompt was left empty.');
return false;
};
foo(userName);

Categories