Javascript-Returning a value from a prompt - javascript

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);

Related

Returning name as a string in Javascript

Going through a course on learning Javascript. The problem asks me to return my name as string. Here is an solution guide they've given me but I'm confused on what I'm missing. Here is what I have so far, but could use help on a step by step on how to solve it.
Guide :
describe("Solution", () => {
it("should return a string as a name", () => {
const name = getUserName();
if (typeof name === "string") {
console.log(`Hello, ${name}!`);
}
expect(name).to.be.a("string");
});
});
**my solution so far: **
function getUserName("Jawwad") {
let name = getUserName()
if (typeof name === String) {
console.log("Hello " + name);
}
return name;
}
I'm expecting it to return my name as string
A few problems with your logic:
You can't call a function inside of the same function.
It doesn't make sense to have a function receive as an argument the name it returns, for example: it would make sense to receive a name as argument and then do something with it like printing.
Here is an example derived from your code:
//innitial name
let theName = "Jonh"
// function purpose is to print the name
function printName(_theName) {
if (typeof _theName === 'string') { //string has to be in quotations
console.log("Hello " + _theName);
}
}
//calling function outside of itself
printName(theName);

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).

basic function within object return

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'.

How to call a function on string jQuery

I was reading through fluent api I got a doubt.
I want to take in a string upon which a jQuery function or example is called upon
Function
function compareThis(newString) {
function compare(newString) {
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
}
}
Where it is called as
("alerting").compareThis("alerted").compare(); //alert 'different string'
I want to pass the data/string not as parameter but as called upon.
JSFiddle
Note: I would like to call the function in similar cases like finding date interval etc
You can use prototype to add function to String class:
String.prototype.compare = function(newString){
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
};
I think you should adapt the code for your function, but it's the idea.
Maybe I missed interpreted however, it looks as it you required a form of method chaining to compare string. To do this you can create a variable and create functions inside it.
var compare = (function(){
var thisString;
var stringToCompare;
var create = function(sVal) {
thisString = sVal;
return this;
};
// Public
var compareThis = function(sVal) {
stringToCompare = sVal;
return this;
};
var compare = function(anotherString) {
return thisString == stringToCompare;
};
return {
create: create,
compareThis: compareThis,
compare: compare
};
}());
var b = compare.create('test').compareThis('test').compare();
alert(b);
Example fiddle

Invalid left-hand side in assignment for simple login script

I have to build a simple login script for a js class.
I cannot get the loop to work. Everytime I type in any info it gives me "Invalid left-hand side in assignment"
When the login button is clicked the getData function gets the values of the boxes then passes them to the logon function that checks against the array. That's where the script stops. If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
What am I doing wrong?
<script type="text/javascript">
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass = userLogins[i].password && user = userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
If I change the = in the if statement to == it will accept the last valid login f the array but none of the others.
= is the assignment operator
== is the equality operator
You're confusing the two. You want the latter. Otherwise, your assigning the value which results returns the value itself (often a true value).
Per the comments, there's also the strict equality operator. For the difference between == and === this answer will blow your mind.

Categories