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)}">`
Related
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 />': ''}
I haven't found the right answer in any similar questions, so I hope someone may be able to point me in the right direction.
I have a simple script that updates some text based on a range slider selection. I have noticed this works in everything except Edge, and having little experience with Javascript I'm wondering how to fix it.
The HTML:
<input type="range" min="1" max="3" step="1" id="pick_fruit" onchange="updateTextInput(this.value);" oninput="amount.value=rangeInput.value">
<p id="fruit_value">Pick a fruit</p>
The script:
<script type="text/javascript">
function updateTextInput() {
var fruit_range = Number(document.getElementById("pick_fruit").value);
var fruit_value = "";
if (
fruit_range === 1 ) {
fruit_value = "Apples";
}
else if (
fruit_range === 2 ) {
fruit_value = "Oranges";
}
else if (
fruit_range === 3 ) {
fruit_value = "Pears";
}
document.getElementById('fruit_value').innerHTML = fruit_value;
}
</script>
Any help would be much appreciated.
Thanks in advance
Use the oninput event to trigger the function. An object that maps ints to strings cleans up the conditional a little...
const fruitMap = { 1:'Apples', 2:'Oranges', 3:'Pears' }
function updateTextInput() {
const v = +document.getElementById("pick_fruit").value
document.getElementById('fruit_value').innerHTML = fruitMap[v];
}
<input type="range" min="1" max="3" step="1" id="pick_fruit"
oninput="updateTextInput()">
<p id="fruit_value">Pick a fruit</p>
You don't need to add
var fruit_range = Number(document.getElementById("pick_fruit").value);
because you are already getting value from the your function (updateTextInput()), you need to provide an argument inside the function to get the onchange value. I tried to simplify the code you can test it.
<html>
<body>
<input type="range" min="1" max="3" step="1" id="pick_fruit" onchange="updateTextInput(this.value)">
<p id="fruit_value">Pick a fruit</p>
</body>
<script type="text/javascript">
var fruit_value = "";
function updateTextInput(value) {
if (value == 1 ) {
this.fruit_value = "Apples";
}
else if (value == 2 ) {
this.fruit_value = "Oranges";
}
else if (value == 3 ) {
this.fruit_value = "Pears";
}
document.getElementById('fruit_value').innerHTML = fruit_value;
}
</script>
</html>
Update
Also you need to change the conditions from "===" to "==" or change the min & max to number type, as in input tag the values are in string and "===" checks both and its type but as in condition you were comparing string type to number type it will always give a empty string .
I am new to JavaScript and trying to create a form that will take the user to a sub-domain based their input. User enters a string, selects a value from a drowdown menu. Once user clicks submit, they will be taken to a custom URL based on their input.
For some reason my IF statement doesn't work and prefix is always equals to a1.
Here is the code:
<script type="text/javascript">
function goToPage() {
var prefix;
if (document.getElementById('model').value = 93) {
prefix = "a1";
}
else if (document.getElementById('model').value = 95) {
prefix = "a2";
}
else {
prefix = "a3";
}
window.location = "https://example.com/" + prefix + "/" + document.getElementById('string').value;
}
</script>
<input type="text" id="string" />
<select id="model" />
<option value="93" />9-3</option>
<option value="95" />9-5</option>
<option value="96" />9-6</option>
</select>
<input type="submit" value="submit" onclick="goToPage();" />
You are using assignment operator (=) in the condition, that's why the condition always evaluates to true. You have to use the comparison operator (== or ===).
Please Note: Since the input values are of type string and you are comparing that with number, it is better to convert them to number before the comparison. Also the HTML tags (select and option) you are using closes them in the start tag itself (as if they are self-closing) which is not valid HTML syntax.
Try the following way:
function goToPage() {
var elValue = Number(document.getElementById('model').value);
var prefix;
if (elValue == 93) {
prefix = "a1";
}
else if (elValue == 95) {
prefix = "a2";
}
else {
prefix = "a3";
}
window.location = "https://example.com/" + prefix + "/" + document.getElementById('string').value;
}
<input type="text" id="string" />
<select id="model">
<option value="93">9-3</option>
<option value="95">9-5</option>
<option value="96">9-6</option>
</select>
<input type="submit" value="submit" onclick="goToPage();" />
Don't use assignment operators. Single equation marks means assignment operator. Use double equal marks in conditions.
if (document.getElementById('model').value == 93)
I am trying to make a simple calculator. You enter one number, you enter the second one, press PLUS and get alert with an answer. I need to show alert('no data') if you click on PLUS when input fields are not touched.
function num1() {
nm = document.getElementById('nsum1').value;
}
function num2() {
mn = document.getElementById('nsum2').value;
}
function plus() {
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
} else {
alert(sum);
}
}
<input onchange="num1()" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input onchange="num2()" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
So far I have tried if(sum == undefined)/if(sum == null)/if(sum == false)/if(isNaN(sum))/if(sum == "") and nothing seems to work.
If you haven't touched the input field and get the value, then the result would be ""
You need a condition like
if (nm == "" || mn == "") {
alert('no data');
}
And also you should do operation after validations. You are doing operation and then validating.
Fixed other issues aswell.
function plus() {
mn = document.getElementById('nsum2').value;
nm = document.getElementById('nsum1').value;
if (nm == "" || mn == "") {
alert('no data');
} else {
sum = +nm + +mn;
alert(sum);
}
}
<input id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
You can do it much easier
function plus(num1, num2) {
alert(isNaN(num1) || isNaN(num2) ? 'No data' : num1 + num2);
}
function getNumber(id) {
return parseFloat(document.getElementById(id).value);
}
<input id="nsum1" type="number" placeholder="number" maxlength="6" />
<span onclick="plus(getNumber('nsum1'), getNumber('nsum2'))" id="sum">PLUS</span>
<input id="nsum2" type="number" placeholder="number" maxlength="6" />
I've made some changes to your code to make it more robust. See the inline comments for a description.
Declare variables
It is important to declare your variables, when you don't all the variables you are using will wind up in the global scope. When you Google this you will find many articles like this one: https://gist.github.com/hallettj/64478.
Prevent polluting the global scope. In a small website this may not be much of an issue but when working on larger project or with third party code, this is a must. The link above also explains this to some extend.
Use a button If you want something to be interactive, use an HTML element that was meant for it. The button element should be used, it has all sorts of accessibility features the span doesn't have. For instance, by default it will receive focus when navigating your website with the tab key.
Use descriptive variable names nm and mn may mean something to you now but in 6 months it will be a complete mystery. It also makes the code more readable and thus easier to maintain.
Attach event listeners in JS In general it is a bad idea to assign event listeners through the HTML attribute onXXX="". It is more error prone and a lot more time intensive when you want to change something.
// Wrap your code in a closure to prevent poluting the global scope.
(function() {
// Always declare your variables. These variables are no longer scoped to the window object but are no scoped to the function we're in.
var
valueA = null,
valueB = null;
/**
* To check if your input is a valid number requires a couple of checks.
* It is best to place these into their own method so you're other
* method is more readable.
*/
function isNumber(value) {
if (
// == null checks for undefined and null
value == null ||
value === '' ||
isNaN(value)
) {
return false;
}
return true;
}
function onChangeHandler(event) {
var
// Get the element that dispatched the event.
target = event.target;
// Check if the target has the class we've assigned to the inputs, of not you can ignore the event.
if (!target.classList.contains('js-input')) {
return;
}
// Based on the ID of the target, assign the value to one of the variables for the values.
switch(target.id) {
case 'nsum1':
valueA = parseFloat(target.value);
break;
case 'nsum2':
valueB = parseFloat(target.value);
break;
}
}
function onSumTriggerClicked(event) {
// Check if there are numbers to work with
if (
!isNumber(valueA) ||
!isNumber(valueB)
) {
// If not alert the user
alert('no data');
return;
}
sum = valueA + valueB;
alert(sum);
}
function init() {
var
// Get the calculator element.
calculator = document.getElementById('calculator'),
// Get the button to sum up the value.
sumButton = document.getElementById('sum-trigger');
// Add an event listener for the change event.
calculator.addEventListener('change', onChangeHandler);
// Add an event listener for the click event.
sumButton.addEventListener('click', onSumTriggerClicked);
}
// Call the init method.
init();
})();
<div id="calculator">
<input class="js-input" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<button type="button" id="sum-trigger" id="sum">PLUS</button>
<input class="js-input" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
</div>
Try to track it via Inspector, maybe log the values of nm and mn before anything else and correct your condition accordingly(as the sample).
function plus() {
console.log(nm);
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
}
It will most likely just be blank. So in this case you can modify your condition into:
if (nm === '' || mn === '') {...}
Hope it will help
Please use this as reference.
I've fixed your code.
if ( num1 === '' && num2 === '' ) {
alert('no data');
} else {
alert( parseInt(num1) + parseInt(num2) );
}
Utilizing ASP with DotNetNuke to loop through listing of repeating radio buttons.
Utilizing JQuery
Currently displaying proper result value for weightCalculations function (ex: 3)
How do I combine the rbtCalculations results with the weightCalculations results?
Ex: IF rbtCalculations = Very High AND weightCalculations = High THEN
$('p.custom' + ID).text("5");
<input id="rbt_0" name="rbt" value="Very High" checked="checked" onclick="rbtCalculations(this,6559);" type="radio">
<input id="rbt_1" name="rbt" value="High" onclick="rbtCalculations(this,6559);" type="radio">
<input id="stakeholders_rbt_0" name="stakeholders_rbt" value="Very High" onclick="weightCalculations(this,6559);" type="radio">
<input id="stakeholders_rbt_1" name="stakeholders_rbt" value="High" checked="checked" onclick="weightCalculations(this,6559);" type="radio">
<input id="stakeholders_rbt_2" name="stakeholders_rbt" value="Low to Moderate" onclick="weightCalculations(this,6559);" type="radio">
<p class="custom6559">3</p>
<script type="text/javascript">
function weightCalculations(value, ID) {
if (value.value == "High") {
$('p.custom' + ID).text("3");
}
else {
$('p.custom' + ID).text("2");
}
}
I'd probably just add a class to the radio buttons to identify them and a wrapping element to associate all the parts together:
<div class="js-weight-calc-wrap">
<input type="radio" class="js-rbt" ... />
<input type="radio" class="js-rbt" ... />
<input type="radio" class="js-weight" ... />
<input type="radio" class="js-weight" ... />
<input type="radio" class="js-weight" ... />
<p class="js-result custom6559"></p>
</div>
<script>
jQuery(document).ready(function ($) {
$('.js-rbt, .js-weight').change(function () {
var $this = $(this),
$wrap = $this.closest('.js-weight-calc-wrap'),
rbtVal = $wrap.find('.js-rbt:checked').val(),
weightVal = $wrap.find('.js-weight:checked').val(),
result = rbtVal === 'VeryHigh' && weightVal === 'High'
? '5'
: rbtVal === 'VeryHigh' && weightVal === 'Low'
? '4'
: '0';
$wrap.find('.js-result').text(result)
});
});
</script>
I'd also probably end up create a jQuery plugin to contain all of that logic, so on your page it'd just be a call like this:
jQuery(function ($) {
$('.js-weight-calc-wrap').weightCalculator({
rbtSelector: '.js-rbt',
weightSelector: '.js-weight',
resultSelector: '.js-result'
});
});
UPDATE
I'd forgotten before that you need to filter the radio buttons when you select them, so that you get the checked one only (was confusing with a <select/> element). After adding :select to the selector, it works as expected. I cleaned it up a little more, and created a working jsFiddle.
function weightCalculations(value, ID) {
if (value.value === "High" && $('input[name="rbt"]').val() === "Very High") {
$('p.custom' + ID).text("5");
}
else if(value.value === "High"){
$('p.custom' + ID).text("3");
}
else {
$('p.custom' + ID).text("2");
}
}