I am using a simple if/else to check if a value is greater than another value, and display an appropriate message.
Looks like this:
$.post('api/getHeaderBudgetvsTarget.php', {headercriteria:headercriteria}, function(data) {
let obj = JSON.parse(data);
let totalbudget = obj[0].budget; // set to 1600
let totaltarget = obj[0].target; // set to 300
if(totaltarget > totalbudget) {
console.log('greater');
} else if(totaltarget < totalbudget) {
console.log('lesser');
}
});
Looking at the above logic, it should be clear to see that the console should display "lesser", because totaltarget(300) is not greater than totalbudget(1600).
But it's not. For some reason, it's saying that totaltarget(300) is greater than totalbudget(1600) - and I cannot figure out why.
My PHP script, getHeaderBudgetvsTarget.php, is not doing anything special. Just a simple query that does some calculations, as follows:
<?php
$sql = "SELECT
( SELECT ROUND(SUM(budget)) FROM `budget` ) AS 'budget',
( SELECT ROUND(SUM(`average`)) FROM `main` ) AS 'target',
( SELECT ROUND(SUM(`totalcheck`)) FROM `main` ) - ( SELECT ROUND( SUM(`budget`) ) FROM `budget` ) AS `budgetvstotalcheck`";
?>
Nothing special.
I checked the database design. The only difference I could find was the budget column in the budget table is set to a decimal.
The average column in the main table is set to a mediumint.
I don't think either one of those settings really make a difference (let me know if otherwise).
I am completely perplexed as to why this is happening.
I did attempt the following:
if($.isNumeric(totalbudget)) {
console.log('true');
} else {
console.log('false');
}
I checked both variables, and both appear to be numeric.
Why is this particular greater/lesser than logic not working?
Refer to the docs:
$.isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers
So $.isNumeric("300") is still true. You should convert your variables into number before comparing them like:
if (+totaltarget > +totalbudget)...
Related
I want to enter an multiple field entered data in table with for loop
but i am getting an error in the post method.
error is
count(): Parameter must be an array or an object that implements Countable
controller code :-
$degree = $request->degree;
for($i=0;$i<count($degree);$i++){
$edu = new education;
$edu->degree = $request->degree[i];
$edu->clg = $request->clg[i];
$edu->yoc = $request->yoc[i];
$edu->save();
}
so, please suggest me what i can do.
Here not at all big problem,
you can not use count for the one value the array is required for
that i think that you have not been enterd dynamically many values it can be 0
so replace code in your controller:-
$degree = $request->degree;
if($degree > 0)
{
for($i=0;$i<count($degree);$i++){
$edu = new education;
$edu->degree = $request->degree[i];
$edu->clg = $request->clg[i];
$edu->yoc = $request->yoc[i];
$edu->save();
}
}
here i have used $degree if its value is greater then 0 that means
if it has value count grater then one then you can only go for loop and add value to database
otherwise it will be not go in for loop
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.
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
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.