I am programming in Polymer 1.0 and am trying to create an IF function to change the value of a property. My function is the following:
_searchButton: function(selectednamedropdown, selectedtypedropdown){
if (selectednamedropdown=="no_name_selected" && selectedtypedropdown=="no_type_selected"){
this.searchUsagesBtn = true
} else{
this.searchUsagesBtn = false
}
}
In my mind when selectednamedropdown is equal to "no_name_selected" and selectedtypedropdown is equal to "no_type_selected" the function should set searchUsagesBtn to true and when they are not these values, false.
However, the function does not ever seem to be returning true even when these conditions are met. Any ideas why this might be? Thanks for all help
When I run your function like this:
let searchUsagesBtn;
function search(selectednamedropdown, selectedtypedropdown) {
if (
selectednamedropdown === "no_name_selected" &&
selectedtypedropdown === "no_type_selected"
) {
searchUsagesBtn = true;
} else {
searchUsagesBtn = false;
}
}
search("no_name_selected", "no_type_selected");
console.log("button: ", searchUsagesBtn);
I get button: true in console log. So maybe your inputs in this function are not a strings.
The issue was around how JavaScript treats properties within functions. The function was storing the new value and old value of the first property and not any values of the second property. The solution involved making 2 functions to test the strings in each property. Thanks for all assistance
Related
I have a list of variables that I call tags. Each one changes value from true to false depending on the function executed. These 'tags' act as builder pieces for booleans that I'd like to add in other variables. Basically, I'm trying to shorthand the language in order to make complex boolean conditions. Is this code correct for Javascript? The conditions are not passing as I've intended. cleared would read as true while runScreen and runIndicator read as true
Update I shortened the code and made a function to help strengthen the emphasis on the issue. Please see the code below.
Thanks
//builder variables for condition
let testValueA;
let testValueB;
//condition shorthanded inside a variable
const testCondition = !testValueA && testValueB;
// test function for condition
function testCondionValue() {
testValueA=Math.random() > 0.5;
testValueB=Math.random() > 0.5;
console.log("testValueA is", testValueA, "and testValueB is", testValueB);
if (testCondition) {
console.log(" therefore testCondition is true")
}
else {
console.log("therefore testCondition is false")
}
}
This line:
var cleared = (noHover && !runScreen && !runIndicator);
runScreen is true, then !runScreen is false, then cleared is false.
Somehow I couldn't get my comparison operators working. I have the following piece of code:
function handleNotifClickRemind(key) {
localStorage.setItem('no_remind_change_pwd', true);
notification.close(key);
}
// ...
<Button outline size="small" onClick={() => handleNotifClickRemind(key)}>
Dont remind me
</Button>
// ...
console.log(localStorage.getItem('no_remind_change_pwd'));
function another_func(data) {
if (localStorage.getItem('no_remind_change_pwd') != true) {
openNotification('topRight');
}
}
When I clicked the "Don't remind me" button, handleNotifClickRemind was triggered because the log output on the third section prints true. However, openNotification was still being triggered. Can anyone please help?
P.S. I didn't initialize the value, I just let no_remind_change_pwd be null.
Thanks in advance.
All you've saved in localstorage are strings.
So you are comparing "true"!=true which is always true.
If you want to compare the value, you can use like the following.
JSON.parse(localStorage.getItem('no_remind_change_pwd')) != true
That means, the following is true
console.log(JSON.parse("true") === true)
It's always good practice to use triple comparison operator like === or !==.
localStorage.getItem() return data in String format so if you want to compare with some boolean then first convert it to boolean. By Boolean(localStorage.getItem('no_remind_change_pwd')).
function another_func(data) {
if (Boolean(localStorage.getItem('no_remind_change_pwd')) !== true) {
openNotification('topRight');
}
}
Hope this should clear your understanding.
My question might be a little unclear. Same questions were also asked before but I couldn't figure out how to solve mine by reading them. I need more clear guidance:
I have already created three functions to check colors. (I don't have issues with them. I am not including them here because of the size.)
Lets assume we have three working functions like that:
function checkHex(input) {
// returns boolean value if input is hex color
}
checkHex("#1234a6"); // returns true
function checkRGB(input) {
// returns boolean value if input is RGB color
}
checkRGB("rgb(255, 255, 112)"); // returns true
function checkHSL(input) {
// returns boolean value if input is hsl color
}
checkHSL("hsl(122, 1, 1)"); // returns true
I am having 4th function (checkColor) which has mixed color values to check:
function checkColor(input) {
// returns boolean value if input belong to right color value
}
checkColor("#ccccff"); // should return true
checkColor("rgb(255,255,200)"); // should return true
checkColor("hls(46,0.66,0.21)"); // should return true
QUESTION: Do I have to include all three functions(checkHex,checkRGB,checkHSL) into the 4th one (checkColor)? How do I do that. I researched about that and tried couple ways to solve but I couldn't.
I am trying to do it without using RegExp. I am new to programming, never merged multiple functions before.
Any additional resource you can share with me about "combining multiple functions" will help me a lot too.
Thank you for your time and effort in advance !
The first 3 functions you built are often called predicates. There are a bunch of great ways to group predicates but #FelixKling mentions the simplest in the comments. You could also create functions specifically for this purpose.
// composition function
const any = (...predicates) => subject => predicates.reduce((state, predicate) => (state || predicate(subject)), false);
// predicates
const biggerThan5 = x => x>5;
const isOdd = x => !!(x % 2);
// results and usage
console.log(any(biggerThan5, isOdd)(10)); // true
console.log(any(biggerThan5, isOdd)(2)); // false
You shouldn't include functions into other functions, you just can use them inside of other ones.
For example:
function checkColor(input) {
var isHex = checkHex(input), //store the result of function
isRGB = checkRGB(input), //store the result of function
isHLS = checkHSL(input); //store the result of function
return isHex || isRGB || isHLS; //returns true if one of the options is true.
}
function checkHex(input) {
// returns boolean value if input is hex color
}
function checkRGB(input) {
// returns boolean value if input is RGB color
}
function checkHSL(input) {
// returns boolean value if input is hsl color
}
I have a fullcalendar where I display non-editable events which are collected from a google calendar, or from a database. Then I want to register customer requests for events from the calendar. This works, but I am not able to list only the events that are added by the user.
Any hint on how to do this?
I tried this:
function retrieve_events() {
var rdv=$('#calendar').fullCalendar( 'clientEvents', undefined);
for (i=0; i<=rdv.length-1; i++) {
/*alert(rdv.toSource());*/
alert(rdv[i].title+" id: "+rdv[i].id+" start: "+rdv[i].start+" end:"+rdv[i].end+" heldag:"+rdv[i].allDay);
}
}
The the "undefined" as id, means that I have given all the non-editable events an id, while the new ones haven't got one. But this way I get all events listed, even those without an id. The same happens with null and ''. But using hardcoded id-numbers returns that specific event.
I see from the documentation that there seems to be other ways to get hold of the events I need, by using other criteria like classes. However I cannot figure out how to specify this filter.
I haven't worked with FullCalendar yet nor do I intend to extensively test this, so I cannot guarantee that this will work.
However, why don't you simple test whether rdv[i].id evaluates to false?
Try:
function retrieve_events( ) {
var rdv = $('#calendar').fullCalendar('clientEvents'),
results = [];
for( var i = 0; i < rdv.length; ++i ) {
if( !rdv[i].id ) {
results.push(rdv[i]);
}
}
return results;
}
P.S.: Passing undefined to .fullCalendar() probably is redundant. It would be equivalent to passing only a single variable. I'd guess the second parameter is a type of events that you can filter for, but passing only a single parameter would cause the plugin to return all events. Also, note that !!'' === false.
The internal check whether the second parameter is set is probably similar to this:
$.fn.fullCalendar = function( command ) {
switch( command ) {
// ... some case's
case 'clientEvents':
var filter = arguments[1];
if( !filter ) {
// Retrieve ALL client events
}
else {
// Filter client events
}
break;
// ... some more case's
}
};
This does not compare types. Testing filter === false would only return true, if filter would evaluate to false and is a boolean.
Following are examples of values that evaluate to false. There may be more, but I believe those are all.
undefined
null
0
false
''
I'm running into a maddening problem where I set a variable to point to a jQuery selector, such as: var foobar=jQuery(this); I then pass this variable to a function to be worked on. Let's simplify a little and say the function looks like this:
function SetFieldValue (selector) {
selector.val('test');
console.log ( selector );
console.log ( jQuery('#' + selector.attr('id')) );
}
In this situation if you assume that:
the selector is always a form element (and therefore val() is a valid operation)
the selector does resolve to a single dom element which has an 'id' attribute
You would then expect the two console.log statements to output the same result, right? Well I'm running into a situation where this condition only happens about 90% of the time.
In order to give more context I've created a short screencast demonstrating the problem:
SCREENCAST LINK
For reference purposes, here's the actual SetFieldValue code that is shown in the screencast:
function SetFieldValue ( domObject, value ) {
// as a safety function, check if a string representation of the domObject was passed in and convert it to a jQuery object if it was
if ( jQuery.type(domObject) === "string") {
console.log ("Value passed into SetFieldValue was a string representation so converting to jQuery object");
domObject = jQuery(domObject);
}
if ( jQuery.inArray (domObject.prop('tagName').toLowerCase(),['input' , 'select' , 'textarea']) >= 0 ) {
console.log ("setting to value attribute: " + value);
if ( domObject.hasAttr('id') ) {
domObject.val(value);
//jQuery('#' + domObject.attr('id')).val(value);
} else {
domObject.attr('value',value);
}
console.log ("Using jQuery ID it is set to: " + jQuery('#' + domObject.attr('id')).val() );
console.log ("Using jQuery selector variable it is set to: " + domObject.val() );
} else {
console.log ("setting to html attribute");
domObject.html( value );
}
return domObject;
}
Lets examine the code a bit.
First assigning back to a parameter is not a good practice adding a var at the start of your function would be a lot better, as scope can be lost.
//Suggestion change parameter to domItem
var domObject
Your missing an error handler for when the parameter is not String.
when identifying the type use
<VARNAME>.constructor.toString().match(/function (\w*)/)[1] === "<TYPE>"
It's more efficient and handles custom types.
No need for all the logic in assignment of value attribute. Any dom Object can be made to have a value attribute. also not sure why you are setting the val versus the value.
domObject.attr('value',value);
It is at this point that I can see your code could really use some documentation to help explain purpose
If you are explicitly only wanting to set value on Input fields and set value as innerhtml on non input fields then yes the logic would be needed but could be simplified to ... as the value doesn't need to be detected to overwritten.
if (jQuery.inArray (domObject.prop('tagName').toLowerCase(), ['input' , 'select' , 'textarea']) >= 0) {
domObject.attr('value',value);
} else {
domObject.html( value );
}
No Idea why you are returning the domObject out.
So a quick rewrite without the return and keeping most of the logic adding error handling results in
/*jslint sloppy: true*/
/*global jQuery*/
function SetFieldValue(domString, value) {
// as a safety function, check if a string representation of the domObjects was passed in and convert it to a jQuery object if it was
var domObjects, index;
//errorhandling
if (domString === undefined || domString === null) {
throw {error : "domString must have a value."};
}
if (domString.constructor.toString().match(/function (\w*)/)[1] !== "string") {
if (domString.constructor.toString().match(/function (\w*)/)[1].match(/HTML[a-zA-Z]*Element/) === null) {
throw {error : "domString expected to be String or domObjects"};
}
} else {
if (jQuery(domString).length === 0) {
throw {error : "domString does not resolve to a detectable domObjects."};
}
}
//errorhandling
//action
if (domString.constructor.toString().match(/function (\w*)/)[1].match(/HTML[a-zA-Z]*Element/)) {
//made as an array to normalize as jQuery returns an array allows code to be simplified
domObjects = [domString];
} else {
domObjects = jQuery(domString);
}
//given that domObjects are an array need to step through the array
for (index = domObjects.length - 1; index >= 0; index -= 1) {
if (
jQuery.inArray(
domObjects[index].tagName.toLowerCase(),
['input', 'select', 'textarea']
) >= 0
) {
if (domObjects[index].hasAttr('id')) {
domObjects[index].val(value);
} else {
domObjects[index].attr('value', value);
}
} else {
domObjects[index].html(value);
}
}
}
The above passes JSLint
I know I didn't provide enough context for people to really dig into this problem but I have in the end solved it. What was the issue? Well it was #Kobi who first asked is the DOM element's ID unique ... to which I happily reported it was. And it had been but in fact that WAS the problem. Jesus. It's always the obvious things that you then go onto overlook that get you in trouble.
Anyway, thanks for your patience and help.