Why won't this specific function work? - javascript

Create a function called whichChild that takes one parameter: a child's name.
When passed in ‘Dave’ return ‘Oldest’
When passed in ‘Michelle’ return ‘Middle’
When given any other value return ‘Not my kid!”
function whichChild(achildsname){
var name = prompt ("Which Child?");
if (name == "Dave") {
prompt("Oldest");
}
else if (name == "Michelle"){
prompt("Middle");
}
else (name /= "Dave" && "Michelle"){
prompt("Not My Kid!");
}
}
Ok redo! How am I supposed to make this function take one parameter? I need it to take one parameter: a child's name. Im supposed to create this function for a test. Any help would be much appreciated. Thank you.

function whichChild(){
var name = prompt("Which Child?");
if (name === "Dave") {
console.log("Oldest");
}
else if (name === "Michelle"){
console.log("Middle");
}
else {
console.log("Not My Kid!");
}
}
whichChild();
You don't need the parameter, because there is no need of calling an argument in the function. Instead of prompt, use console.log, I assume you are trying to display a message after the user has prompted a name, so, it would not be appropriate to have a prompt after another prompt, when the only thing you need is a response,"whichChild();" will invoke that function.

I believe this is what you want:
function whichChild() {
var name = prompt("Which Child?");
if (name == "Dave") {
alert("Oldest");
} else if (name == "Michelle") {
alert("Middle");
} else {
alert("Not My Kid!");
}
}
whichChild();

Related

How to nest an if-statement inside a function? - Javascript

Now that I have a recursive function, I wonder what is best in order for the same flow to continue.
Nest an another function, isn't it?
In other words, I would like another prompt that asks the user's age when the user answers yes to the first prompt.
The issue that I'm facing now is that the last prompt does not comeback if the user writes something different than "yes" or "no".
They way I've nested it makes the prompts pop up in a way that I can't figure out:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
function showPrompt(firstQuestion) {
var age = prompt(firstQuestion).toLowerCase();
if (age < 21) {
alert("You're too young. Go home.");
} else if (age >= 21) {
alert("Welcome.");
} else {
showPrompt(firstQuestion);
}
}
showPrompt("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?");
The problem is that you are overwriting your function. If you give your second function another name I guess it works the way you want. And as given in the other answer, you do not need to define your function in the condotional clause:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
nextQuestion("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
function nextQuestion(secondQuestion) {
var age = parseInt(prompt(secondQuestion));
if (typeof age == "number" && age < 21) {
alert("You're too young. Go home.");
} else if (typeof age == "number" && age >= 21) {
alert("Welcome.");
} else {
showPrompt(secondQuestion);
}
}
showPrompt("Do you like gambling?");
Your problem is the conditional creation of showPrompt within the function called showPrompt, see Function declarations inside if/else statements?. While such declarations are allowed, they have side effects and should be avoided.
One side effect is that the conditional function declaration creates a local variable that is undefined unless execution enters the if block and assigns it a value. In the OP, the local showPrompt declaration shadows the global showPrompt created by the global function declaration. Hence if the block is not entered, when it's called, its value is undefined and a TypeError is thrown, e.g.
// Global foo
var foo = 23;
function bar() {
// Declaration creates a local foo even if
// if block is not entered
if (false) {
function foo (){}
}
// foo is undefined
console.log(typeof foo);
}
bar();
To fix that, change the name of the function in the if block and move it out of the block.
Also, as pointed out by epascarello, you should do numeric comparisons using numbers, not strings. When using comparison operators, if one of the values is a number, then the other will be converted to number too for the comparison. But if they are both strings (prompt returns a string), they'll be compared as strings. But for readability, it's best to use numbers for both sides.
Finally, you should test the value returned by the prompt to see it's a string. If the user clicks "Cancel", it will return null and calling toLowerCase will throw an error. So if the value isn't a string, the user clicked cancel and the function should handle it (e.g. exit).
function showPrompt(msg) {
function showPrompt2(firstQuestion) {
var age = prompt(firstQuestion);
if (typeof age != 'string') {
return;
}
if (+age < 21) {
alert("You're too young. Go home.");
} else if (+age >= 21) {
alert("Welcome.");
} else {
showPrompt2(firstQuestion);
}
}
var str = prompt(msg);
if (typeof str != 'string') {
return;
}
str = str.toLowerCase();
if (str === "yes") {
showPrompt2("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?")

if statement is not returning expected result Javascript

I wrote a small script after learning a bit about the object constructor and I wanted to take it a step further with this code, but the if statement isn't behaving as expected... All I want to know is why? I understand this kind of script isn't a normal thing in Javascript... but I believe that the === is evaluating to true, thus printing dave in the alert box, no matter what I enter, and not following through the if statement conditions.
var dave, jason, nick, get;
get = prompt('Input your Name', 'Name Here')
var Person = function (name, birthYear, job) {
this.name = name;
this.birthYear = birthYear;
this.job = job;
};
dave = new Person('Dave', 1976, 'Showman');
jason = new Person('Jason', 1987, 'Novice');
nick = new Person('Nick', 1993, 'Cable-tech');
function printObj(object) {
var output = '';
for (var property in object) {
output += property + ': ' + object[property] + '\n';
}
alert(output);
}
if (get.toLowerCase === 'dave'.toLowerCase) {
printObj(dave);
} else if (get.toLowerCase === 'jason'.toLowerCase) {
printObj(jason);
} else if (get.toLowerCase === 'nick'.toLowerCase) {
printObj(nick);
} else {
alert('Not a defined object')
}
Something else obvious I might be doing wrong is the comparison... but that's how it was explained to me in javascript on freenode, because at first that was my issue, which is still kind of it I suppose. I think I'm simply doing something obviously messy, appreciate any insight I receive, the MDN and W3 only explain so much.
get.toLowerCase() is a method, and should be invoked with the open and closed parenthesis. The way it is currently written is checking whether the method is equal to the same method on a different string instance.
if (get.toLowerCase() === 'dave') {
printObj(dave);
} else if (get.toLowerCase() === 'jason') {
printObj(jason);
} else if (get.toLowerCase() === 'nick') {
printObj(nick);
} else {
alert('Not a defined object')
}
Since you are comparing to a lowercase string, you don't need to call toLowerCase() on 'dave', 'jason', or 'nick'. I think you may have meant to compare to the value stored in the variables dave, jason, and nick.
if (get.toLowerCase() === dave.name.toLowerCase()) {
printObj(dave);
} else if (get.toLowerCase() === jason.name.toLowerCase()) {
printObj(jason);
} else if (get.toLowerCase() === nick.name.toLowerCase()) {
printObj(nick);
} else {
alert('Not a defined object')
}
Last, you should not name a variable get. get is reserved in ES6 so as browser start to natively support it, your code will do some very odd things. I suggest something like userInput.
var dave, jason, nick, userInput;
userInput = prompt('Input your Name', 'Name Here')
//...other code...
if (userInput.toLowerCase() === dave.name.toLowerCase()) {
printObj(dave);
} else if (userInput.toLowerCase() === jason.name.toLowerCase()) {
printObj(jason);
} else if (userInput.toLowerCase() === nick.name.toLowerCase()) {
printObj(nick);
} else {
alert('Not a defined object')
}
You are using the .toLowerCase() method the wrong way. Also, you are using the get
Your Code:
var dave, jason, nick, get;
get = prompt('Input your Name', 'Name Here')
// other code
if (get.toLowerCase === 'dave'.toLowerCase) {
printObj(dave);
} else if (get.toLowerCase === 'jason'.toLowerCase) {
printObj(jason);
} else if (get.toLowerCase === 'nick'.toLowerCase) {
printObj(nick);
} else {
alert('Not a defined object')
}
As you can see on your code your .toLowerCase method misses the (). And please do not use the get as a variable name because get is a keyword.
Try this:
var dave, jason, nick, inputValue;
inputValue = prompt('Input your Name', 'Name Here')
// other code
if (inputValue.toLowerCase() === 'dave'.toLowerCase()) {
printObj(dave);
} else if (inputValue.toLowerCase() === 'jason'.toLowerCase()) {
printObj(jason);
} else if (inputValue.toLowerCase() === 'nick'.toLowerCase()) {
printObj(nick);
} else {
alert('Not a defined object')
}
Also, if you are comparing an own defined comparison there's no need to add the .toLowerCase(). You actually want to compare the input value (which is an unknown format ei. upper case or lower case) to a lower case string value that you want to compared of.
Use this:
if (get.toLowerCase === 'dave')
instead of
if (get.toLowerCase === 'dave'.toLowerCase())

Only execute function if value is NOT empty [duplicate]

This question already has answers here:
How to check if a value is not null and not empty string in JS
(11 answers)
Closed 4 years ago.
I have the following html, which is part of a webform:
<input type="hidden" name="userID" id="control_COLUMN43" value="%%userID%%">
The value of this field is dynamically generated by a database. It's possible that the value of this field is empty.
Next to this, I created a function which sends the value of this field (via Ajax) to another database, upon a submit of the webform.
What I want to do now is: only execute this function if the value of the field "userID" is NOT empty. If it's empty, I don't want this function to be executed.
So I assume it will be something like this, but I'm struggling to find the correct way to do this:
if (#control_COLUMN43 !=== "") //this is the id of the field
{
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
Or the other way around I guess?
Can anybody help me with this?
Thanks in advance!
Use like this
// Also u can add null check
if(data !== '') {
// do something
}
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
You should not declare functions inside the conditions. If you do then at the time of execution if the condition is not met, function will not be available which may lead to errors. Hence, you should place the condition inside the function.
You can modify your condition to following
function SendAjax() {
if (document.getEelementById("control_COLUMN43").value) {
//code
}
}
You can access the value of the input by using getElementById(id).value
and declare your function outside the if block like:
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
if (document.getElementById('txt_name').value) //this is the id of the field
{
SendAjax()
}
else
{
//don't execute function
}
The if statement you need, without JQuery, should be like this:
if (document.getElementById("control_COLUMN43").value !=== "") {
// .. commands
}
First get your hidden input value using document.getElementById() and then check if it is null like following:
var userId = document.getElementById("control_COLUMN43");
if (userId) //this is the id of the field
{
SendAjax()
}
else
{
alert("UserId is null);
}
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
In if condition check $("#control_COLUMN43").val()
It can be null or '' so you can apply condition accordingly.
You can check empty value like this
function isEmpty(str) {
return (!str || 0 === str.length);
}
var val = document.getElementById('control_COLUMN43').value;
var col = isEmpty(val);
if (col) {
function SendAjax(){
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
There are several issues at once:
You are mixing up declaring a function with calling it.
To get the value from a control, use document.getElementById("...").value
The proper notation for not === is !==.
This is how it goes:
// Declare the function
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
// Get value
var value = document.getElementById("control_COLUMN43").value;
// Call the function conditionally
if (value !== "")
{
SendAjax();
}
The code you write in if condition is not correct ID value must be get like:
if(document.getElementById("control_COLUMN43").value != ''){
//Your code here
}
Basically you have to check value property of the input element. Using dom selectors first you can select a element using id then you can access value attribute for element. If it's not null or undefined or just empty spaces then you can call your function
function handleClick(){
// Extract value from input element
let val = document.getElementById('input').value;
// Check value is empty or not
if(val){
// If not empty
console.log('Value is : ' + val);
}
else{
// If empty
console.log('Empty input');
}
}
<input id="input" type="text">
<button onclick="handleClick()">SUBMIT</button>
// get the contents of the form element
var control_COLUMN43 = document.getElementById("control_COLUMN43").value;
// process the data
if( control_COLUMN43 != "" ) {......

How to check on a button click which function was last called out of many custom functions in javascript?

The first method sets the array of objects in the variable final,the second method sets the array of objects in the variable final1.In this particular save method I want to check in the else condition which method was called last(method1 or method2) so that I can decide which variable should I use inside fetchItemId function?
function save(){
if (final === undefined && final1 !== "")
fetchItemId(final1);
if (final1 === undefined && final !== "")
fetchItemId(final);
else {
// I want to call the last executed method out of 2
}
}
You can use a flag variable to check this.
Eg
var i=0;
method1()
{
//whatever
i=1;
}
method2()
{
//whatever
i=2;
}
In your else check value of i.
if(i=1)
// method1 was called last
else
if(i=2)
//method2 was called last
else if (i=0)
// none was called

"return false;" for form submission is not working

"return false;" for form submission is working for the rest of my code, just not this section. Any ideas why?
function checkForm() {
$("select[name*=lic_company]").each(function() {
if($(this).val() != '') {
var i1 = $(this).parent("td").next("td").children("select");
var i2 = i1.parent("td").next("td").children("input");
var i3 = i2.parent("td").next("td").children("input");
if(i1.val() == '') {
i1.parent("td").addClass("formErrorTD");
i1.addClass("formError");
alert("You must enter a state for this license");
return false;
}
if(i2.val() == '') {
i2.parent("td").addClass("formErrorTD");
i2.addClass("formError");
alert("You must enter an expiration date for this license");
return false;
}
if(i3.val() == '') {
i3.parent("td").addClass("formErrorTD");
i3.addClass("formError");
alert("You must enter a license number for this license");
return false;
}
}
});
}
and it's being called by
$("#addAgentForm").submit(checkForm);
You are calling return false; within a closure that is an argument passed to .each. Therefore, .each is capturing the return false;. To get around this you need need to have a boolean flag that holds the state of the form:
function checkForm() {
var okay = true;
$("select[name*=lic_company]").each(function() {
...
return okay = false;
...
});
return okay;
}
And everything will work fine.
Your return false statements are inside the anonymous function passed to .each(), so only return a value from that function, not the entire call to checkForm().
If I had to guess, it's because you're returning from the function passed to your each call, meaning all you're really doing is exiting your each function while your main validation function finishes without a hitch.

Categories

Resources