If Value Equals None Don't Call Function
Posted: Thu Apr 03, 2014 3:47 am
Someone recently asked me this question so I thought I'd write a simple tutorial on it.
There's a variety of reasons as to why this is necessary.
First we need to call and if else statement.
We need to say that if our value is "equal to" empty we tell the user why this is. Usually the case is there's no data to add. Will just put down "function denied". However if it does have a value we can use our else statement to apply whatever function we need.
Here's how it's done using JQuery. (See it in action here)
There's a variety of reasons as to why this is necessary.
First we need to call and if else statement.
We need to say that if our value is "equal to" empty we tell the user why this is. Usually the case is there's no data to add. Will just put down "function denied". However if it does have a value we can use our else statement to apply whatever function we need.
Here's how it's done using JQuery. (See it in action here)
Code: Select all
and here is how it's done in standalone Javascript.
$(document).ready(function() {
$(".call").on('click', function() {
if ( $(".code").val() === "" ) {
alert("Function denied!");
} else {
alert("Function accepted!");
}
});
});
Code: Select all
Now other times you may need to use this type of functionality but you can't use an if else statement. This is where conditional (aka ternary) operators become a relevant use.
document.addEventListener('DOMContentLoaded', function() {
var code = document.querySelector('.code'),
call = document.querySelector('.call');
call.addEventListener('click', function() {
if ( code.value === "" ) {
alert("Function denied!");
} else {
alert("Function accepted!");
}
});
});
Code: Select all
Here's an example of how a conditional operator is used.
<condition> ? <true-value> : <false-value>
Code: Select all
"+ $(".add-css-selector-val").val() +" {"+ ( $(".grab-pos-top").val() === "" ? "" : "{ top:" + value + ";}\n" ) + "