I can't seem to get my code to check which user role I've selected from the drop down. I don't often use for this so I'm kind of running into some trouble with it I think. Let me know if I'm missing something? I left the console.log()'s in but they haven't returned anything.
var userRole = "";
if ($('select[name=custom1]').find(':selected').val("") === "Healthcare Practitioner") {
return userRole = "SR-Practitioner";
console.log(userRole);
} else {
return userRole = "SR-Educator";
console.log(userRole);
};
A return statement is an exit point of a function. Everything after the return statement won't be executed. One exception is code that are wrapped in a try finally block. Therefore the console.log won't be executed.
Like #MDeSchaepmeester wrote: a .val(arg) call is a setter not a getter. Please read the documentation of .val(): http://api.jquery.com/val/
if ($('select[name=custom1]').find(':selected').val() === "Healthcare Practitioner") {
return "SR-Practitioner";
} else {
return "SR-Educator";
};
or
var userRole = '';
if ($('select[name=custom1]').find(':selected').val() === "Healthcare Practitioner") {
userRole = "SR-Practitioner";
} else {
userRole "SR-Educator";
};
console.log(userRole);
Related
Please excuse how utterly "noobish" I am, I'm trying to learn as I go along but I'm very new.
I have the below code which I'm trying to use for a Discord bot. For the most part it works, however the # "ping" simply returns "#undefined" as opposed to the values I've set in the consts.
Would anyone be so kind as to point me in the right direction on this?
const ping = {
roleID: function() {
return this.role;
}
}
const John = {
role:"abc"
}
const Mary = {
role:"123"
}
function pingSubbed() {
let pingID = message.author.username;
if (pingID == "John") {
ping.roleID.call(John);
}
if (pingID == "Mary") {
ping.roleID.call(Mary);
}
}
yield hook.send(`**${message.author.username}**\n` + " " + messageContents + " " + "#"+pingSubbed());
I'm expecting the function pingSubbed() to determine the username of the person who posts in Discord, for example John, reference the above ping.roleID.call(John) and then take the appropriate role (in this case John = abc) and sending this information as a message itself - #123 - as in the last line "#"+pingSubbed()
You might find a look up table simpler to author and maintain:
function pingSubbed() {
let getId = Function.call.bind(ping.roleID);
return {
John: getId(John),
Mary: getId(Mary),
}[message.author.username] || ("Unknown User:"+message.author.username);
}
This puts a lot less boilerplate (even no quotes) in the way of your raw logic.
Even more jedi would be to make an iterable object containing your users instead of free-floating variables (well const(s)). This drastically simplifies the already-simpler look up table method:
const ping = {
roleID: function() {
return this.role;
}
}
const users={
John : {
role:"abc"
},
Mary: {
role:"123"
}
}
function pingSubbed() {
return ping.roleID.call(users[message.author.username]) ||
("Unknown User:"+message.author.username);
}
that gets it to the point of being almost all data with minimal logic and code to worry about...
The call inside your Object is working well you just forget to return the value that you need from your function
function pingSubbed() {
let pingID = message.author.username;
if (pingID == "John") {
ping.roleID.call(John);
}
if (pingID == "Mary") {
ping.roleID.call(Mary);
}
return pingID // add this line
}
When you use this keyword inside an object, it refers to the object itself.
So, I created "javascript code" variable in GTM and trying to get clientID via ga.getAll, and have the following code:
function foo() {
var trackers = ga.getAll();
if (trackers.length > 0) {
return trackers[0].get('trackingId') === 'UA-188398635-1' ? trackers[0].get('clientId') : 'nonon';
}
}
But it always returns undefined, even if I make it return a string constant 'asdasd' - having ga.getAll in the code is enough for the function to break. And the most confusing thing - the same code works in debug console just fine. Help please.
Since foo returns undefined, that means that trackers.length is 0. Try this:
function foo() {
var trackers = ga.getAll();
if(trackers.length >0) {
return trackers[0].get('trackingId') === 'UA-188082465-1' ? trackers[0].get('clientId') : 'nonon';
} else {
return 'This is not undefined';
}
}
I am working through a code challenge and I need to return a string into a variable if the guess passed in attemptAnswer(guess) matches the answer property's value. My test is failing currently saying that the variable response is undefined.
Is this some sort of binding issue?
...curious how this problem could be resolved.
Thank you!
class Sphinx {
constructor() {
this.name = null;
this.riddles = [];
}
collectRiddle(riddle) {
this.riddles.push(riddle);
if (this.riddles.length > 3) { this.riddles.shift() };
}
attemptAnswer(guess) {
this.riddles.forEach( (element, index) => {
if (guess === element.answer) {
this.riddles.splice(index, 1);
return "That wasn't that hard, I bet you don't get the next one."
};
})
}
}
//test
const response = sphinx.attemptAnswer('short');
assert.equal(response, 'That wasn\'t that hard, I bet you don\'t get the next one');
When you return in attemptAnswer() you're actually retuning to the inner forEach callback function you defined: (element, index) => {..., not the outer attemptAnswer() method.
Instead of immediately returning within your forEach loop, you can set a variable outside this loop called result, and then return the result once your forEach loop is complete.
Also, currently, you're not creating a new instance of Sphinx, which means you don't have an object which can call the attemptAnswer() method. To fix this add new Sphinx() to create a new Sphinx object.
See example below:
class Sphinx {
constructor() {
this.name = null;
this.riddles = [{"answer":"short"}];
}
collectRiddle(riddle) {
this.riddles.push(riddle);
if (this.riddles.length > 3) {
this.riddles.shift()
};
}
attemptAnswer(guess) {
let res = "";
this.riddles.forEach((element, index) => {
if (guess === element.answer && !res) {
// no need for splice as it will skip an entry
res = "That wasn't that hard, I bet you don't get the next one.";
};
})
return res;
}
}
const response = new Sphinx();
response.collectRiddle({"answer":"short"});
console.log(response.attemptAnswer('short'));
you're never calling collectRiddle so this.riddles is always [] and the forEach block is never entered, therefore, not returning anything, so, the return value is undefined
you should have a variable called found right before the loop, if you find a match, set it to truethen return the string depending on the found variable :
note : the string inside the function is different from the one you're comparing it to (it has backslashes and ends with a dot) so the test will always be falsy
class Sphinx {
constructor() {
this.name = null;
this.riddles = [];
}
collectRiddle(riddle) {
this.riddles.push(riddle);
if (this.riddles.length > 3) {
this.riddles.shift()
};
}
attemptAnswer(guess) {
var found = false;
this.riddles.forEach((element, index) => {
if (guess === element.answer) {
found = true;
}
})
return found ? "Woohoo" : "That wasn't that hard, I bet you don't get the next one."
}
}
//test
const s = new Sphinx();
const response = s.attemptAnswer('short');
console.log(response === `That wasn't that hard, I bet you don't get the next one.`);
I assume you already did const sphynx = new Sphynx().
attemptAnswer() doesn't return anything, in Javascript, if you don't return anything, you basically return undefined. So it is normal that response is undefined.
In your case, I would use for-loop, instead of forEach.
attemptAnswer(guess) {
for (let i = 0; i < this.riddles.length; i++) {
if (guess === this.riddles[i].answer) {
this.riddles.splice(index, 1);
return "That wasn't that hard, I bet you don't get the next one.";
}
}
return "Not found";
}
Using .splice() inside forEach is not recommended
using forEach, will go through all the items inside the array, even if you already found your answer.
I could be wording this a bit weird. Let me lay out some code to help explain. I'm writing a simple react component. This react component has a form where I submit a form. This is what I have so far:
onSubmit(event){
event.preventDefault()
if (this.checkQuantity()){
// this is what i want to be simpler, the return value i want is already in the checkQuantity function in the if condition
return true
} else {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
}
}
checkQuantity(){
if (this.state.quantity > this.props.item.quantity){
alert("Can't buy what's not there!")
return true
} else {
return false
}
}
Like the comment states above, I just want the execution of the form submission to stop. I guess, I'm just looking for best practice in this type of situation. One where I'd like to abstract functionality but use the return value of that abstracted functionality in a conditional as a return.
I'd write
onSubmit(event) {
event.preventDefault()
if (!this.checkQuantity()) {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
}
}
checkQuantity() {
const isToomuch = this.state.quantity > this.props.item.quantity;
if (isToomuch) {
alert("Can't buy what's not there!")
}
return isToomuch
}
Or maybe you want to put the alert inside the onSubmit method, then checkQuantity becomes even simpler. Also you might want to rename checkQuantity to something more descriptive, like isInvalidQuantity.
onSubmit(event){
event.preventDefault()
return checkQuantity();
}
checkQuantity(){
if (this.state.quantity > this.props.item.quantity){
alert("Can't buy what's not there!")
return true
} else {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
return false
}
}
The problem here is you don't just want to return the value of checkQauntity(), you want to act on the return value and then decide what to do. In this case, the code you have is as good as any way of doing it.
But for a more general case (where you are not just returning true or false, you could do something like the following:
onSubmit(event){
event.preventDefault();
var check = checkQuantity();
if (check > 6 ){
return check;
}
else {
//do something else..
}
}
checkQuantity(){
var someNumber = ...someNumber;
return someNumber;
}
I feel that you are splitting functions unnecessarily. Wouldn't the following code be enough?
onSubmit(event){
event.preventDefault()
if (this.state.quantity > this.props.item.quantity){
alert("Can't buy what's not there!")
} else {
let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)
}
}
Also, like others mentioned, the return value has not significance in your example because you are not checking it.
I'm new to JavaScript so I apologize if this is simple. I'm passing a couple values to my controller but after, I need to reset the global variables without refreshing the page. My code looks like this:
var userName = null;
var _delegated = false;
function setAddtionalData(value) {
if(value == true) {
userName = "something";
_delegated = value;
}
}
function getAdditionalData() {
return {
username: userName,
delegated: _delegated
};
userName = null; // Does not get hit
_delegated = false; // Does not get hit
}
But variables never get updated. Is there a way to set these without page a refresh?
Code after the return will not be executed. You need to grab the values, clear the variables, and return the grabbed values:
function getAdditionalData() {
var retval = {
username: userName,
delegated: _delegated
};
userName = null;
_delegated = false;
return retval;
}
Those values are never reached since your return statement exits out of the function.
You should save, username and _delegated to temporary variables, set them to null, and then return the object.
return statements are used to exit out of a function, so anything you put after your return statement will not happen.