Default beginning value of innerHTML of a div - javascript

In my app, I need to check if a div container is empty before appending certain text elements to it (the innerHTML is created and removed many times in my app, hence the need to check for emptiness). The div is created very simply as below in the beginning. Why doesn't checking for an empty string as below work? I am expecting the alert to show the text Nothing, but it does not.
let targetContainer = document.getElementById("container")
let containerText = targetContainer.innerHTML
alert("Text: " + containerText == "" ? "Nothing" : containerText)
#container {
background-color: #0f2e0c;
}
<div id="container"></div>

Your main issue is with operator precedence. Currently, you code is evaluating like so:
("Text: " + containerText) == "" ? "Nothing" : containerText
in your code + has higher operator precedence than ==, meaning that the concatenation occurs before the == occurs. You can force the evaluation of the equality and the ternary to occur before the addition concatenation occurs by wrapping it in parenthesis to group your ternary operation. Since grouping has the highest operator precedence it will occur before your concatenation occurs:
"Text: " + (containerText == "" ? "Nothing" : containerText)
let targetContainer = document.getElementById("container")
let containerText = targetContainer.innerHTML
alert("Text: " + (containerText == "" ? "Nothing" : containerText));
#container {
background-color: #0f2e0c;
}
<div id="container"></div>

Related

React. What is the wrong with my ternar operator in className?

So, I have a simple tag span with classNames that trigger on a special condition, but for some reason my class in the DOM does not appear. I got just class word without anything like <span class>...</span>.
My span tag:
<span key={total} className={'total' + ' ' + total === 0 ? 'total--empty' : ' '}>
{total ? total : 0}
</span>
It is parsed like a ternary* : (statement) ? whenTrue : whenFalse;
// Which, translated to your code makes:
{ ('total' + ' ' + total === 0) ? 'total--empty' : ' '}
A string is truthy, thus 'total--empty'. What you need:
{ 'total' + ' ' + (total === 0 ? 'total--empty' : ' ')}
* Most people call it the ternary operator, but it is actually called the conditional operator. It's a ternary operator (an operator accepting three operands), and currently JavaScript's only ternary operator, but that could change.
You should probably know about concept of Operator precedence.
In your case, you are using '+' operator (precedence of 13) and comparison '===' operator (precedence of 10).
Therefore, the expression:
{'total' + ' ' + total === 0 ? 'total--empty' : ' '}
...will always return falsy value i.e. space.
Lets say total value is 0, so your expression executes as 'total'+' '+0 which becomes a string "total 0" NOT EQUAL TO 0.
What you need to do is Grouping of expression using '()' round brackets (precedence of 20).
i.e.
{'total' + ' ' + (total === 0 ? 'total--empty' : ' ')}
which has possible truthy/falsy outcome i.e. "total " or "total total--empty"
You can try this below. We can make it with the help of curly braces and parenthesis.
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
Parenthesis ( ) can be used to return something.
Curly braces versus parenthesis in ReactJS
<span className={"total "+(total !== 0 ? "total_empty": null )} />
{total ? total : 0}
</span>

Conditional logic jsx react

I am trying to apply more than 1 condition to className in my jsx view. However it won't let me.
It only listens to the first condition.
className={usernameFocus ? "toggled" : "" || usernameValidated ? "validated" : ""}
I have tried several combinations:
className={usernameFocus ? "toggled" : "" + usernameValidated ? "validated" : ""}
How could I accomplish more than one conditional to add classNames to my element?
Your order of operations is mixed up. Put your separate conditions in parentheses. Also, you can short-circuit the class evaluation like this:
className={(usernameFocus && "toggled") + " " + (usernameValidated && "validated")}
If you feel extra fancy, you can also use a template string:
className={`${usernameFocus && "toggled"} ${usernameValidated && "validated"}`}
If you do this a lot (multiple booleans), have a look at the officially recommended classnames module by Jed Watson. Link.
With it, you can do it like this:
var usernameClasses = classNames({
'validated': usernameValidated,
'toggled': usernameFocus
});
className={usernameClasses};
I think you are missing a space between the class names for when both are applied, also brackets help with multiple nested conditional statements.
Try this:
className={(usernameFocus ? "toggled" : "") + " " + (usernameValidated ? "validated" : "")}

Checking for null in JavaScript works except for zero

I'm using the following syntax to ensure that my input parameters aren't null.
function hazaa(shazoo){
shazoo = shazoo || " ";
}
It works for everything I tested for except the zero.
null -> " "
"beep" -> "beep"
4 -> 4
but...
0 -> " "
I'm guessing that the zero is regarded as null or false, hence creating the gotcha. What's the syntax to get it right, so that zero is zero?
If it makes the issue considerably simpler to suggest a syntax, we can assume that the input is going to be a char, string, number or null.
I'm using the following syntax to ensure that my input parameters aren't null.
If all you are trying to do is to use " " only if the input is null, then use ternary operator, like this
shazoo = shazoo === null ? " " : shazoo;
This answer lists the values which are considered as Falsy in JavaScript. The table shows that zeroes are considered as Falsy. That is why shazoo || " " is evaluated to be " ", when shazoo is zero.
In my opinion, this is one of the few places where you don't want to do a typesafe comparison.
In such places you want to threat undefined the same way as null; and you don't want to write it every time.
//so better use this
shazoo = shazoo == null ? " " : shazoo;
//than this
shazoo = shazoo === null || shazoo === undefined ? " " : shazoo;
I'm guessing that the zero is regarded as null or false
Yes 0 is treated as false.
What's the syntax to get it right, so that zero is zero?
You can try to use
shazoo = shazoo === null ? " " : shazoo;
You can us === operator and the best way would be
if (shazoo === null)
shazoo = " ";
No need to use else
shazoo = shazoo //no sense
Use the following:
if (shazoo === null){
...
}else{
...
}
New notation
You can also in ES6 use the default argument notation that will default if undefined is passed for that argument.
function foo(shazoo = "default"){
console.log(shazoo);
}
foo(); // "default"
foo(undefined); // "default"
var bar; //
foo(bar); // "default"
foo("my string"); // "my string"
foo(null); // null
It does not handle null
Boolean(0) outputs false, so it took second option ""
you can try (check this fiddle)
function hazaa(shazoo){
return shazoo == null ? " " : shazoo;
}
hazaa(0); //output 0

The if statement not working properly in Javascript

I am trying to create a logic that if anyone enters "<p>" and "</p>" characters inside <textarea>, then only Jquery should show the win message.I have a textarea with class html, a h2 with class result which shows win or loss.By now, I have this code:
var html = $('.html').val();
if(html.indexOf("</p>" && "<p>") === -1)
{
document.getElementById("result").innerHTML = "You lost it.";
}
else{
document.getElementById("result").innerHTML = "Hurray!You won";
}
But, this code is only checking if the <p> is there and not checking for </p>.So what can I do....
The expression "</p>" && "<p>" is equivalent to "<p>" -- && evaluates each of its arguments from left to right, and returns the last truthy argument. Since both strings are truthy, what you wrote is effectively:
if (html.indexOf("<p>") === -1)
If you want to test whether a string contains two substrings, you have to call indexOf separately for each of them:
if (html.index("</p>") !== -1 && html.indexOf("<p>") !== -1)
From MDN (Logical Operators) - Logical And (&&):
Returns expr1 if it can be converted to false; otherwise, returns
expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
</p> isn't being evaluated as false, so the second value is returned which is <p>.
This means that you're only checking for the index of <p>. Try this instead:
var html = $('.html').val();
if (html.indexOf("</p>") === -1 && html.indexOf("<p>") === -1) {
document.getElementById("result").innerHTML = "You lost it.";
}
else {
document.getElementById("result").innerHTML = "Hurray! You won";
}
.indexOf takes a single string as an argument. You cannot combine string elements together using && like that.
The simplest way to modify your code would be to make two separate checks, one for the opening tag and one for the close:
if (html.indexOf("</p>") !== -1 && html.indexOf("<p>") !== -1)
This makes two separate checks for the two strings.
Alternatively, you could create a jQuery object from the HTML fragment inside your <textarea>, then check that it has no children that are <p> tags:
if ($('<div>'+html+'</div>').find('p').length > 0) {
// the textarea contains some <p> tags
}

How can I tell between a blank textbox and a textbox with zero in it in JavaScript?

I have the following:
var NewCount = document.getElementById('MainContent_gv_NewCount_' + rowIndex).value;
if (NewCount != "") {
document.getElementById('MainContent_gv_lblTotal_' + rowIndex).innerHTML = "£" + ((originalCount - NewCount) * unitCost).toFixed(2);
} else {
document.getElementById('MainContent_gv_lblTotal_' + rowIndex).innerHTML = "";
}
The calculations I am doing are based on the value in the textbox. (NewCount).
I want the label to update if the value is any number (including 0), but to be wiped if the user clears the textbox. However, at the moment it is treating a blank textbox and a textbox with 0 in it the same.
How can I differentiate between the two?
Use !== in your if statement.
I can't reproduce the behavior you are describing. In my tests a textbox with "0" in it will be considered not blank by Javascript using your comparison logic (!= "").
Here is my attempt:
http://jsfiddle.net/pJgyu/5404/
Any of the following could work
NewCount.length > 0
NewCount !== ''
if ( NewCount.length == 0 ) {
// text-box is empty
} else if ( !isNaN(NewCount) ) {
// the value is a number
}

Categories

Resources