Conditional line break - javascript

I only want to line break if variable var is not a null value, how would I go about this?
<div>
{var && `${var}`} <br />
{var2 && `${var2}`}
</div>

Like any other conditional element
<div>
{var && `${var}`}
{var && <br />}
{var2 && `${var2}`}
</div>
Or shorter,
<div>
{var && <>{`${var}`}<br /></>}
{var2 && `${var2}`}
</div>

If you are only checking for null
{var !== null ? '<br />' : ''}
If any falsy statement is the condition you want to check (undefined , null , NaN , 0 , "" , and false)
{var ? '<br />' : ''}

You are creating HTML in JavaScript, so I assume you have used back-ticks around opening and closing div first. Then based on the value of var, You want to set the break point.
First thing is var is a keyword in Javascript and should not be used as the variable name.
Second is we can do something like this using ES6 back-ticks and interpolation.
let myVaribale = 23; // Not Null
const htmlTest = `<div>
<span>Testing the line-break</span>
${myVaribale && `<br/>` }
<p> Life is a test</p>
</div>`;
document.body.innerHTML = htmlTest;
<html>
</html>

Try using
{var ? '<br />': ''}

Related

why I can not use && in javascript for not blank and not space

I want to check the value is not blank or one empty space so I wrote a code
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>
You can update your condition as below.
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() == "") {
alert("empty");
}
If you want to get alert if OccLocation is not empty then :
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() != "") {
alert("not empty");
}
Your condition is wrong.
You have to use == instead of !=.
If you use && then both condition should be true to return true, which is ultimately impossible at the same time in this case. Use || instead, this will be evaluated as true if any of the condition is true.
The condition should be:
if (OccLocation.value ==" " || OccLocation.value == "")
Even you can simplify the condition by using String.prototype.trim()
:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
Try
if (OccLocation.value.trim() == "")
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim()== ""){
alert ("empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass" />
You are checking that it is not empty, then alerting that it is empty. I think you mean to check that it is empty. Change your JS to the following:
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value === " " || OccLocation.value === "")
{
alert ("empty");
}
Your code runs immediately, and the value="" sets it to empty.
Here, I set the value in the markup so it has some, thus it alerts.
var OccLocation = document.getElementById("HdnOccLocation");
console.log(OccLocation.value)
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="dd" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>

How to use _or_ condition in template strings?

I'm creating a project using node.js. I'm using yo-yo library to create html templates.
I want to add a cover from tweet user profile_banner_url.
Like this:
const yo = require('yo-yo')
module.exports = function (tweet) {
return yo`
<div class='cover'>
<img src='${tweet.user.profile_banner_url}' />
</div>
`
}
However, sometimes tweets don't return any profile_banner_url, which gives an error in browser.
I tried to add a different image from public directory:
<img src='${tweet.user.profile_banner_url} || otherimg.jpg' />
But it didn't work.
What is the best approache to use or condition in template strings?
You're looking for
`<div class='cover'>
<img src='${tweet.user.profile_banner_url || 'otherimg.jpg'}' />
</div>`
Notice that the part inside the ${…} is just a regular javascript expression.
I guess now it's possible to use the nullish coalescing operator like
<img src="${some_url ?? 'publicurl.jpg'}" />
Or a regular ternary
<img src="${some_url !== undefined ? some_url : 'public.jpg'}" />
I found this solution for my case
`<input class="range-slider__slider" type="range" ${ ( (inputType) => {
if(inputType == 'temperature')
return 'min="-10" max="30" value="23" data-type="' + inputType +'"';
else if(inputType == 'light')
return 'min="0" max="1000" value="300" data-type="' + inputType +'"';
else if(inputType == 'floor')
return 'input(type="range" min="0" max="30" value="23" data-type="' + inputType + '"';
else
return ''
} )(inputType)}">`

javascript function in javascript function

I have some little code that I can't get to work. Here it is:
<input type='password' name='Confirmpwd' id='Confirmpwd'
onkeyup="if(this.value != '') myFunction('checkConfirmpwd', (Password.value == this.value) ? 1 : 0;, this.id);" />
I'm 100% sure that Password.value and this.value are correct when I place them in there. So it's not a problem with the variables.
The problem is that, myFunction isn;t executed anymore when I try to compare Password.value and this.value in the argument like above. myFunction is declared like this:
myFunction(val1, val2, val3) { ...some code... }
What my goal is that I can compare the 2 strings and send them to myFunction when I call the function.
The ; indicates an end of statement. If there are missing parameter or brackets that have not been closed when a semi-colon is encountered, it may result in an error.
This is the case in this instance.
Change the code to something like
if(this.value != '') myFunction('checkConfirmpwd', (Password.value == this.value) ? 1 : 0, this.id);
Put the onkeyup in an external javascript file rather than the same HTML file. It's better to do this for ease-of-editing and performance:
HTML
<input type="password" name="Confirmpwd" id="Confirmpwd" />
JS
document.getElementById("Confirmpwd").onkeyup = function () {
"use strict";
if (this.value !== "") { // !== is better than !=
myFunction("checkConfirmpwd", (Password.value === this.value) ? 1 : 0, this.id); // === is better than ==
}
};
And all we did there was change ;, to ,. It was just a typo

complex if statement runs code regardless of condition output

JS
if (isNaN(BDyear) == true || isNaN(BDmonth) == true ||
isNaN(BDday) == true || BDday.length != 2 ||
BDmonth.length != 2 || BDyear.length != 4)
{
document.getElementById("BDyear").value = ''
document.getElementById("BDmonth").value = ''
document.getElementById("BDday").value = ''
document.getElementById("bderror").style.display = "inline"
BDstate = false BDcheck = false
}
HTML
<tr>
<td>שנת לידה</td>
<td>
<input class="text" id="BDyear" maxlength="4" style="width:8%" />&nbsp/&nbsp
<input class="text" id="BDmonth" maxlength="2" style="width:5%" />&nbsp/&nbsp
<input class="text" id="BDday" maxlength="2" style="width:5%" />
<br />
<p id="bderror" style="position:absolute; top:70%; color:red; font:65% arial; display:none">תאריך לידה לא תקין</p>
<p id="bderroryoung" style="position:absolute; top:70%; color:red; font:65% arial; display:none">חובה להיות מעל גיל 13</p>
</td>
</tr>
the script part runs regardless whether i put in the inputs a number or words, with any length and i don't understand why is it running, but i'm suspecting it's the "isNaN" function that is not working correctly from different tries and setups. it's supposed to find out if the content entered is only a numric value that is in the proper length for dd/mm/yyyy and if it's all false it's supposed to leave everything as is and BDcheck var to be true so the next if statement will run
Any suggestions?
Make sure BDyear, BDday and BDmonth actually contain values; you may need to use document.getElementById("BDyear").value inside the isNaN functions. The value is also probably a string, so you may want to try first casting it to a number before checking isNaN like this: isNaN(Number(document.getElementById("BDyear").value)).
Also, isNaN returns a Boolean, so comparing it to true is redundant. You can just write it like if (isNaN(BDyear) || isNaN(BDmonth) || isNaN(BDday) || BDday.length != 2 || BDmonth.length != 2 || BDyear.length != 4), possibly with the changes I just suggested.
Ultimately, the code could look like this:
//assuming BDstate and BDcheck variables are already defined
var year = document.getElementById("BDyear");
var month = document.getElementById("BDmonth");
var day = document.getElementById("BDday");
if (isNaN(Number(year.value)) || isNaN(Number(month.value) || isNaN(Number(day.value)) || day.value.length != 2 || month.value.length != 2 || year.value.length != 4)
{
year.value = ''
month.value = ''
day.value = ''
document.getElementById("bderror").style.display = "inline"
BDstate = false
BDcheck = false
}
Also, instead of checking that the string length of month is 2 characters, you may want to check whether the numeric value is between a valid range. For example, a user would currently have to enter "06" (without an leading or trailing spaces, btw) in order for the check to succeed, whereas they could enter " 6 " if you were actually checking that the numeric value is within a valid range like (Number(month.value) >= 1 && Number(month.value) <= 12). The same goes for the day and year.

Simple JavaScript not working?

Why isn't this simple JavaScript validation not working ?? The first condition run through but the second isn't going through ??
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function process(){
var val = document.getElementById('usrIN').value;
var uppVer = val.toUpperCase();
if(val == "" || val == NULL){
alert ("Must fill in input");
}else if (val !== uppVer){
alert("Must be upper case");
}
}
</script>
</head>
<body>
<form type="post" id="frmMain" />
<p>Insert name in upper case <input type="text" maxlength="25" id="usrIN"/></p>
<img src="button.jpeg" >
</form>
</body>
In JavaScript, null is lowercase. Also, your use of == "" will also cover a null or undefined variable. Also, you probably didn't mean to do an else if(), you probably meant to just do a second if if there's no dependency on the former failing for the latter to execute.
NULL is not defined in javascript - use null or undefined.
See here:
http://jsfiddle.net/EZqhN/

Categories