How to delete/hide in IF-ELSE statment previouse statements in HTML - html

How can I make that so it will work only one condition at one time? Basically there is a time when A,B, and C can be pick at one time all of them. Example: So if you pick A there should be only one posibility and it is "else if (A != null)", but if there is A and B it should display only "else if (Model.B != null)", but if it is A,B, and C it should display only "else if (Model.SoldOut != null)". So is there any way to do that? Or is there any way to delete A when it display B, and delete A and B when it displays C?
#if (A == null & B == null & C == null)
{
#Resources.Undefined;
}
else if (A != null)
{
#Resources.ResourceManager.GetString(Model.A.GetDisplayValue());
}
else if (Model.B != null)
{
#Model.B
}
else if (Model.SoldOut != null)
{
<p>-</p>
}

You can do it by changing the order of else if statements
#if (A == null & B == null & C == null)
{
#Resources.Undefined;
}
else if (Model.SoldOut != null)
{
<p>-</p>
}
else if (Model.B != null)
{
#Model.B
}
else if (A != null)
{
#Resources.ResourceManager.GetString(Model.A.GetDisplayValue());
}

My attempt at what you're describing is as follows. It's an inversion of your logic.
// IF THEY'RE ALL PICKED
// it should display only "else if (Model.SoldOut != null)"
#if(A && B && C)
{
<p>-</p>
}
// it should display only "else if (Model.B != null)"
else if(A && B)
{
#Model.B
}
// there should be only one posibility and it is "else if (A != null)"
else if(A)
{
#Resources.ResourceManager.GetString(Model.A.GetDisplayValue());
}
else
{
#Resources.Undefined;
}
But, like I said in my comment, it's incredibly difficult to figure out the logic when you're not describing all of the potential cases. E.g. What if 'C' is the only one that's picked? You know?

Related

javascript backtick and jquery not working [duplicate]

How do I determine if variable is undefined or null?
My code is as follows:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
But if I do this, the JavaScript interpreter halts execution.
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined is true, the above code will catch both null and undefined.
The standard way to catch null and undefined simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.
Edit again
The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.
You should not have any references to undeclared variables in your code.
Combining the above answers, it seems the most complete answer would be:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.
if (variable == null) {
// Do stuff, will only match null or undefined, this won't match false
}
if (typeof EmpName != 'undefined' && EmpName) {
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
Probably the shortest way to do this is:
if(EmpName == null) { /* DO SOMETHING */ };
Here is proof:
function check(EmpName) {
if(EmpName == null) { return true; };
return false;
}
var log = (t,a) => console.log(`${t} -> ${check(a)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined"
And here are more details about == (source here)
BONUS: reason why === is more clear than == (look on agc answer)
jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element.
So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:
if (!EmpName) { //do something }
Edited answer: In my opinion, you shouldn't use the function from my below old answer. Instead, you should probably know the type of your variable and use the according to check directly (for example, wondering if an array is empty? just do if(arr.length===0){} etc.). This answer doesn't even answer OP's question.
I've come to write my own function for this. JavaScript is weird.
It is usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note.
function empty(v) {
let type = typeof v;
if (type === 'undefined') {
return true;
}
if (type === 'boolean') {
return !v;
}
if (v === null) {
return true;
}
if (v === undefined) {
return true;
}
if (v instanceof Array) {
if (v.length < 1) {
return true;
}
} else if (type === 'string') {
if (v.length < 1) {
return true;
}
if (v === '0') {
return true;
}
} else if (type === 'object') {
if (Object.keys(v).length < 1) {
return true;
}
} else if (type === 'number') {
if (v === 0) {
return true;
}
}
return false;
}
TypeScript-compatible.
This function should do exactly the same thing like PHP's empty() function (see RETURN VALUES)
Considers undefined, null, false, 0, 0.0, "0" {}, [] as empty.
"0.0", NaN, " ", true are considered non-empty.
The shortest and easiest:
if(!EmpName ){
// DO SOMETHING
}
this will evaluate true if EmpName is:
null
undefined
NaN
empty
string ("")
0
false
If the variable you want to check is a global, do
if (window.yourVarName) {
// Your code here
}
This way to check will not throw an error even if the yourVarName variable doesn't exist.
Example: I want to know if my browser supports History API
if (window.history) {
history.back();
}
How this works:
window is an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If history doesn't exist then window.history returns undefined. undefined is falsey, so code in an if(undefined){} block won't run.
In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
Check all conditions:
if(variable === undefined || variable === null || variable === ''){
}
Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function.
var s; // undefined
jQuery.isEmptyObject(s); // will return true;
s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;
// usage
if(jQuery.isEmptyObject(s)){
alert('Either variable: s is undefined or its value is null');
}else{
alert('variable: s has value ' + s);
}
s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
I've just had this problem i.e. checking if an object is null.
I simply use this:
if (object) {
// Your code
}
For example:
if (document.getElementById("enterJob")) {
document.getElementById("enterJob").className += ' current';
}
You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).
if (x === null || x === undefined) {
// Add your response code here, etc.
}
source: https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/
jQuery check element not null:
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
// Do something
}
else{
// Else do something else
}
With the newest javascript changes, you can use the new logical operator ??= to check if the left operand is null or undefined and if so assign the value of right operand.
SO,
if(EmpName == null){ // if Variable EmpName null or undefined
EmpName = 'some value';
};
Is equivalent to:
EmpName ??= 'some value';
The easiest way to check is:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
I run this test in the Chrome console. Using (void 0) you can check undefined:
var c;
undefined
if (c === void 0) alert();
// output = undefined
var c = 1;
// output = undefined
if (c === void 0) alert();
// output = undefined
// check c value c
// output = 1
if (c === void 0) alert();
// output = undefined
c = undefined;
// output = undefined
if (c === void 0) alert();
// output = undefined
With the solution below:
const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);
console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...
I'm able to check for the following:
null
undefined
NaN
empty
string ("")
0
false
To test if a variable is null or undefined I use the below code.
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
if you create a function to check it:
export function isEmpty (v) {
if (typeof v === "undefined") {
return true;
}
if (v === null) {
return true;
}
if (typeof v === "object" && Object.keys(v).length === 0) {
return true;
}
if (Array.isArray(v) && v.length === 0) {
return true;
}
if (typeof v === "string" && v.trim().length === 0) {
return true;
}
return false;
}
(null == undefined) // true
(null === undefined) // false
Because === checks for both the type and value. Type of both are different but value is the same.
Let's look at this,
let apple; // Only declare the variable as apple
alert(apple); // undefined
In the above, the variable is only declared as apple. In this case, if we call method alert it will display undefined.
let apple = null; /* Declare the variable as apple and initialized but the value is null */
alert(apple); // null
In the second one it displays null, because variable of apple value is null.
So you can check whether a value is undefined or null.
if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...
The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.
Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:
if (foo === void 0 || foo === null) { ... }
You can do something like this, I think its more efficient for multiple value check on the same variable in one condition
const x = undefined;
const y = null;
const z = 'test';
if ([undefined, null].includes(x)) {
// Will return true
}
if ([undefined, null].includes(y)) {
// Will return true
}
if ([undefined, null].includes(z)) {
// Will return false
}
No one seems to have to posted this yet, so here we go:
a?.valueOf() === undefined works reliably for either null or undefined.
The following works pretty much like a == null or a == undefined, but it could be more attractive for purists who don't like == 😎
function check(a) {
const value = a?.valueOf();
if (value === undefined) {
console.log("a is null or undefined");
}
else {
console.log(value);
}
}
check(null);
check(undefined);
check(0);
check("");
check({});
check([]);
On a side note, a?.constructor works too:
function check(a) {
if (a?.constructor === undefined) {
console.log("a is null or undefined");
}
}
check(null);
check(undefined);
check(0);
check("");
check({});
check([]);
Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
You can only use second one: as it will check for both definition and declaration
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
I still think the best/safe way to test these two conditions is to cast the value to a string:
var EmpName = $("div#esd-names div#name").attr('class');
// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
// Do something with your code
}
// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
// Do something with your code
}

Can't get functions to work properly

So I just got started with auto hotkeys and I'm having a bit o trouble getting my functions and variables to play nicely..
This is what I have:
PSbri0 = C:\Controls\Set_0Bri_PS.bat
PSbri50 = C:\Controls\Set_50Bri_PS.bat
PSbri100 = C:\Controls\Set_100Bri_PS.bat
HPbri0 = C:\Controls\Set_0Bri_HP.bat
HPbri50 = C:\Controls\Set_50Bri_HP.bat
HPbri100 = C:\Controls\Set_100Bri_HP.bat
Run %PSbri0%
current_setting := 0
current_power := 0 ;Power Saver = 0 High performance = 1
setPower(){
global current_power
if(%current_power% == 1){
MsgBox Pow 1
%current_power% := 0
}else{
MsgBox pow 2
%current_power% := 1
}
}
getChange(direction)
{
global current_power
MsgBox dir %direction%
if (%current_power% == 0){
;MsgBox run 0
getChangePS(%direction%)
}
else if (%current_power% == 1){
;MsgBox run 1
getChangeHP(%direction%)
}
}
getChangePS(direction)
{
global current_setting
;MsgBox %current_setting%
MsgBox Direction: %direction%
if(direction == 1){
;MsgBox %current_setting%
if(%current_setting% == 0){
}
else if(%current_setting% == 50){
%current_setting% := 0
Run %PSbri0%
}
else if(%current_setting% == 100){
%current_setting% := 50
Run %PSbri50%
}
}
else if(direction == 0){
;MsgBox %current_setting%
if(%current_setting% == 100){
}
else if(%current_setting% == 50){
%current_setting% := 100
Run %PSbri100%
}
else if(%current_setting% == 0){
%current_setting% := 50
Run %PSbri50%
}
}
}
getChangeHP(direction)
{
global
if(direction == 1){
;MsgBox %current_setting%
if(%current_setting% == 0){
}
else if(%current_setting% == 50){
%current_setting% := 0
Run %HPbri0%
}
else if(%current_setting% == 100){
%current_setting% := 50
Run %HPbri50%
}
}
else if(direction == 0){
;MsgBox %current_setting%
if(%current_setting% == 100){
}
else if(%current_setting% == 50){
%current_setting% := 100
Run %HPbri100%
}
else if(%current_setting% == 0){
%current_setting% := 50
Run %HPbri50%
}
}
}
^F5:: getChange(0)
^F6:: getChange(1)
!^P:: setPower()
I've been looking over the documentation and through other posts online but I cannot seem to find out what I'm doing wrong..
My intended goal is to be able to switch power profiles easily I have the 6 profiles declared in the beginning with thee levels of high performance (HP) and three Power Saver levels(PS)
I want to use Alt+Ctrl+P to change between power options and the F5/F6 to add brightness or dim the screen.
The bat files work perfectly and they change my settings as they should so I know that isn't an issue..
I've already tried without the global declaration in the functions first but that didn't work and neither does it with the declaration.
Thanks for your help guys!
Sorry to say but you are using the % in way too many places
Its use depends on where you are using the variable if it in an expression you do not use % around variables, in most other places you do, next thing is then to know when you're typing in something that accepts an expression, that take a little time to learn but here are two links that may help
http://ahkscript.org/docs/Variables.htm#Expressions
http://www.autohotkey.com/board/topic/118109-hard-rules-when-using-variables/
Here is a little example of how it needs to look
setPower(){
global current_power
if (current_power == 1){
MsgBox Pow 1
current_power := 0
}else{
MsgBox pow 2
current_power := 1
}
}
getChange(direction)
{
global current_power
MsgBox dir %direction%
if (current_power == 0){
;MsgBox run 0
getChangePS(direction)
}
else if (current_power == 1){
;MsgBox run 1
getChangeHP(direction)
}
}
Hope it helps

Navigating Windows Phone 8 Pivot

While working on Windows Phone 8 app, we need to restrict user on navigating pivot.
For example, only first two items are available until user make his selection on second item, then third is unlocked, and so on.
I've tried several approaches, and all of them stumble on one thing - setting pivot.SelectedIndex (or pivot.SelectedItem) inside event handler does not changing visual representation of pivot.
What is missing in my approach?
Here is sample code, from one of variants I've tried...
private void ReservationPivot_UnloadingPivotItem(object sender, PivotItemEventArgs e)
{
if (previousSelectedIndex != ((Pivot)sender).Items.IndexOf(e.Item) && !pivotRedirect)
previousSelectedIndex = ((Pivot)sender).Items.IndexOf(e.Item);
else if (previousSelectedIndex == ((Pivot)sender).Items.IndexOf(e.Item))
return;
object tmp;
PhoneApplicationService.Current.State.TryGetValue("PickupAddress", out tmp);
if (e.Item == ((Pivot)sender).Items[1] && tmp == null && !pivotRedirect)
{
MessageBox.Show("Please, select pickup point!");
pivotRedirect = true;
((Pivot)sender).SelectedIndex = previousSelectedIndex;
((Pivot)sender).SelectedItem = ((Pivot)sender).Items[1];
return;
}
PhoneApplicationService.Current.State.TryGetValue("DropOffAddress", out tmp);
if (e.Item == ((Pivot)sender).Items[2] && tmp == null && !pivotRedirect)
{
MessageBox.Show("Please, select dropoff point!");
pivotRedirect = true;
((Pivot)sender).SelectedIndex = previousSelectedIndex;
((Pivot)sender).SelectedItem = ((Pivot)sender).Items[2];
return;
}
if (pivotRedirect)
{
if (((Pivot)sender).SelectedIndex != previousSelectedIndex)
{
pivotRedirect = false;
((Pivot)sender).SelectedIndex = previousSelectedIndex;
}
}
}
Dont have access to visual now but did you try set visible of third pivot item to collapsed and change it to visible when user will select dropooff point ?

Changing Cell Values of DataGridView

Suppose I have the following hypothetical table:
How can I make a DataGridView display the following?
Notice the values of Sick have changed.
I have tried the following to no avail:
var query = from c in Patients
select new
{
c.Name,
c.Sick == 1 ? "Yes" : "No"
};
You can use the DataGridView.CellFormatting event.
private void dataGridView1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Sick")
{
if (e.Value != null)
{
if (e.Value.ToString() == "1"
{
e.Value = "Yes";
}
else
{
e.Value = "No";
}
e.FormattingApplied = true;
}
}
}

Unable to use drag Drop in radtreeview

I have binded all data to RadTreeView but unable to use drag-'n-drop. I used four properties as
IsDragDropEnabled="True"
IsDropPreviewLineEnabled="True"
AllowDrop="True"
IsDragPreviewEnabled="True"
and I want to drop an item within same tree. But it doesnt work.
There is quite a bit of info here : http://www.telerik.com/help/silverlight/raddraganddrop-events.html
But I'm also having trouble with the tree view.
After a quick read of this telerik article, drag-drop seems to be working quite well for me.
<telerik:RadTreeView ... EnableDragAndDrop="true" OnNodeDrop="MyTreeView_NodeDrop">
EnableDragAndDrop and OnNodeDrop seem to be the two vital pieces to getting it working, but weren't in your list of attributes you tried. HTH
<telerik:RadTreeView x:Name="treeView1" IsDragDropEnabled="True" Margin="2,0,0,0" ItemsSource="{Binding SelectedSectionList, Mode=TwoWay}" ItemTemplate="{StaticResource SectionTemplate}" IsEditable="True" SelectedItem="{Binding SelectedCustomSectionList, Mode=TwoWay}" Grid.Column="2">
Now in the code behind
You have to fire event
In Constructor
this.treeView1.AddHandler(RadDragAndDropManager.DropQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnDropQuery), true);
Then
private void OnDropQuery(object sender, DragDropQueryEventArgs e)
{
RadTreeViewItem destinationItem = e.Options.Destination as RadTreeViewItem;
object source = this.GetItemFromPayload<object>(e.Options.Payload);
object target = destinationItem != null ? destinationItem.Item : null;
DropPosition position = destinationItem != null ? destinationItem.DropPosition : DropPosition.Inside;
if (source != null && target != null)
{
Section sourceSection = source as Section;
Section targetSection = target as Section;
Question sourceQuestion = source as Question;
Question targetQuestion = target as Question;
if (sourceQuestion != null)
{
try
{
if (sourceQuestion != null && targetQuestion != null && object.ReferenceEquals(sourceQuestion, targetQuestion))
{
sourceSection.Questions.Remove(sourceQuestion);
targetSection.Questions.Add(sourceQuestion);
e.QueryResult = false;
return;
}
if (targetQuestion != null && position == DropPosition.Inside)
{
sourceSection.Questions.Remove(sourceQuestion);
targetSection.Questions.Add(sourceQuestion);
e.QueryResult = false;
return;
}
if (position != DropPosition.Inside && targetQuestion == null)
{
sourceSection.Questions.Remove(sourceQuestion);
targetSection.Questions.Add(sourceQuestion);
e.QueryResult = false;
return;
}
}
catch (Exception ex)
{
}
}
}
else
{
e.QueryResult = false;
return;
}
e.QueryResult = true;
}
This is it. You will be able to drag and drop.