Writing JQuery / Javascript IF / else statement using Hidden Field Values as - javascript

I'm trying to get a div to be assigned a CSS class based on the value of a hidden field that is loaded via ajax.
My code returns the proper value for the hidden field when called, but my div is always assigned the same css class, regardless of the result.
I'm guessing something is wrong with my IF statement syntax:
function doneLoading(){
var colorStatus = $('#colorStatus').val();
if(colorStatus = 'RED'){
$('.circleFrame').addClass('redState');
}
else if(colorStatus = 'GREEN'){
$('.circleFrame').addClass('greenState');
}
else if(colorStatus = 'YELLOW'){
$('.circleFrame').addClass('yellowState');
}
else {
alert("Something is broken");
}
}

It's because you're doing = assignment instead of == comparison. You may want to use http://jshint.com to help locate these sorts of bugs.
Consider the following alternative to shorten your code.
function doneLoading() {
var color = $('#colorStatus').val().toLowerCase();
$('.circleFrame').addClass(color + 'State');
}
To maintain the validation, you could do this:
var colors = {green:1, red:1, yellow:1};
function doneLoading() {
var color = $('#colorStatus').val().toLowerCase();
if (colors.hasOwnProperty(color))
$('.circleFrame').addClass(color + 'State');
else
alert("Something is broken");
}

You're using the assignment operator instead of the comparison operator.
Try
if(colorStatus === 'RED'){
$('.circleFrame').addClass('redState');
}
instead. (And similarly for the other colours.)

Related

Only execute function if value is NOT empty [duplicate]

This question already has answers here:
How to check if a value is not null and not empty string in JS
(11 answers)
Closed 4 years ago.
I have the following html, which is part of a webform:
<input type="hidden" name="userID" id="control_COLUMN43" value="%%userID%%">
The value of this field is dynamically generated by a database. It's possible that the value of this field is empty.
Next to this, I created a function which sends the value of this field (via Ajax) to another database, upon a submit of the webform.
What I want to do now is: only execute this function if the value of the field "userID" is NOT empty. If it's empty, I don't want this function to be executed.
So I assume it will be something like this, but I'm struggling to find the correct way to do this:
if (#control_COLUMN43 !=== "") //this is the id of the field
{
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
Or the other way around I guess?
Can anybody help me with this?
Thanks in advance!
Use like this
// Also u can add null check
if(data !== '') {
// do something
}
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
You should not declare functions inside the conditions. If you do then at the time of execution if the condition is not met, function will not be available which may lead to errors. Hence, you should place the condition inside the function.
You can modify your condition to following
function SendAjax() {
if (document.getEelementById("control_COLUMN43").value) {
//code
}
}
You can access the value of the input by using getElementById(id).value
and declare your function outside the if block like:
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
if (document.getElementById('txt_name').value) //this is the id of the field
{
SendAjax()
}
else
{
//don't execute function
}
The if statement you need, without JQuery, should be like this:
if (document.getElementById("control_COLUMN43").value !=== "") {
// .. commands
}
First get your hidden input value using document.getElementById() and then check if it is null like following:
var userId = document.getElementById("control_COLUMN43");
if (userId) //this is the id of the field
{
SendAjax()
}
else
{
alert("UserId is null);
}
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
In if condition check $("#control_COLUMN43").val()
It can be null or '' so you can apply condition accordingly.
You can check empty value like this
function isEmpty(str) {
return (!str || 0 === str.length);
}
var val = document.getElementById('control_COLUMN43').value;
var col = isEmpty(val);
if (col) {
function SendAjax(){
if
{
//code
}
else
{
//code
}
}
}
else
{
//don't execute function
}
There are several issues at once:
You are mixing up declaring a function with calling it.
To get the value from a control, use document.getElementById("...").value
The proper notation for not === is !==.
This is how it goes:
// Declare the function
function SendAjax()
{
if
{
//code
}
else
{
//code
}
}
// Get value
var value = document.getElementById("control_COLUMN43").value;
// Call the function conditionally
if (value !== "")
{
SendAjax();
}
The code you write in if condition is not correct ID value must be get like:
if(document.getElementById("control_COLUMN43").value != ''){
//Your code here
}
Basically you have to check value property of the input element. Using dom selectors first you can select a element using id then you can access value attribute for element. If it's not null or undefined or just empty spaces then you can call your function
function handleClick(){
// Extract value from input element
let val = document.getElementById('input').value;
// Check value is empty or not
if(val){
// If not empty
console.log('Value is : ' + val);
}
else{
// If empty
console.log('Empty input');
}
}
<input id="input" type="text">
<button onclick="handleClick()">SUBMIT</button>
// get the contents of the form element
var control_COLUMN43 = document.getElementById("control_COLUMN43").value;
// process the data
if( control_COLUMN43 != "" ) {......

jquery each as 'named function'

I want to use this syntax
var x = function() {
//do something here
}
on an each function
$("#firstname, #surname").each(function( index ) {
if ($(this).val() == '') {
errors += 1;
}
});
Is this possible, and what is this called (I called it 'named functions' is this right)?
EDIT
So something like this
var errors = $("#firstname, #surname").each(function( index ) {
if ($(this).val() == '') {
errors += 1;
}
return errors;
});
console.log("you have".errors()."errors");
When a function is used like this:
$(...).each(function() {
...
});
it is called an anonymous function or lambda function.
I have never heard the term "named function" but I guess you could call it like that, when you assign the function to a variable.
jQuery.each returns like nearly all jQuery-methods the first argument, which is the equivalent of $("#firstname, #surname"). This is very important to understand as it is one of the key-mechanics of jQuery and enables you to do cool stuff like method chaining, e.g. $("#firstname, #surname").each(do something).each(do even more). That means, you can not return your errors in the each method and pass it to a variable outside of the construct.
You could increment a global variable:
var errors = 0
$("#firstname, #surname").map(function() {
if ($(this).val() == '') {
errors++
}
});
console.log("you have" + errors + "errors");
Note the string concatenator +, not ..
Another idea might be to use the jQuery.map method, which indeed enables you to return a value:
var errors = $("#firstname, #surname").map(function() {
if ($(this).val() == '') {
return 1
}
return 0
});
But this would just leave you with an array of 1 and 0 elements which is more or less the same with what you have started. You would need to add another loop to summ the elements together.
Finally let's get to the jQuery.filter method, which should be just what you need:
var errors = $("#firstname, #surname").filter(function() {
return $(this).val() == "";
}).length;
console.log("you have " + errors + " errors");
Filter will return only those elements where the passed function returned a truthy value, so in this case, all elements that had an empty value. You could not only count the elements but immediately highlight the empty form elements:
var errors = $("#firstname, #surname").filter(function() {
return $(this).val() == "";
}).css("background-color", "red").length;
console.log("you have " + errors + " errors");
Your example has a simple solution because you can just use filter and observe the length of the result, but in general, reduce() is the operation to use when you want to aggregate something about all of the items in a collection into a single value.
jQuery doesn't have a reduce() method, but ES5 arrays do, so you could use it like this:
var errorCount = $("#firstname, #surname").toArray().reduce(function(count, item) {
return count + ($(item).val() === '' ? 1 : 0);
}, 0);
As already stated, filter() is what you should be using here, but hopefully this will help you at some point in the future.

Read value or return

Often writing function's code I need to make sure certain values are defined or I want immediately return false value. But writing whole if block feels too much typing. Is it possible to write instead of:
function getSomethingByModel(model) {
var id = model.id;
if (! id) {
return;
}
// rest of the code
}
Something like this:
function getSomethingByModel(model) {
var id = model.id || return;
// rest of the code
}
This is pure aesthetics question, not functional one.
To some extent, you can use the && operator to accomplish this and avoid cumbersome if statements:
function getSomethingByModel(model) {
var id = model && model.id,
thing = id && getThingById(id),
otherThing = thing && getOtherThingFromThing(thing);
return otherThing || null; // or alternatively, just return otherThing;
}
If any stage of the process produces a falsey value, the logic will just quickly fall through to the end and return null (or the first falsey value encountered if you use the alternative return statement above).
You could define all your properties at the top of the function (or wherever, because hoisting), then use the side-effects of assignment to cause a return. For example:
function getSomethingByModel(model) {
var id;
if(!(id = model.id)) return false;
// rest of the code
}

Javascript .click() different for elements w/ same class

I'm pretty new to Javascript/Jquery and am implementing a real simple image carousel for practice and ran into a problem regarding Jquery's "click" method.
The code I currently have is as follows:
$(document.getElementsByClassName("traverse")).click(function() {
if(this.id = "left"){
if (current == 0) {
current = images.length-1;
}
else {
current -= 1;
}
}
else if(this.id = "right") {
if(current = images.length-1) {
current = 0;
}
else {
current += 1;
}
}
$(document.getElementById("image-view")).css("background-image", "url(" + images[current] + ")");
});
With this code there are no errors, but every time I click either the "#right" or "#left" button, they both run code as if "this.id = 'left'". While I understand I can simply separate the two and this will work fine, is there a way I can do it similar to what I have now where I'm applying this event to the class, but differentiating the behavior by the id?
Thanks!
Typo
== to compare
= to assign
Strict equal (===) Returns true if the operands are equal and of the
same type
if(this.id === "left"){
^
and better use
class selector
$('.traverse').click(function(){ .. });
Problem with your code
you are assign this.id = "left" every time in if condition so is condition is always true
if(this.id = "left"){
You're setting this.id to left by only using a single = sign. Try this:
$(document.getElementsByClassName("traverse")).click(function(event) {
if(event.target.id === "left"){
and so on.

storing a value in a variable in conjunction with if

I'm trying to create a talk page link that changes based on what namespace you might be in. For instance if you're in mainspace you'll be directed to Talk: if in category to Category_talk:. I have this so far:
var namespace = if (wgNamespaceNumber == '0') {
return ('Talk');
} else {
return (mw.config.get( 'wgCanonicalNamespace' ) + '_talk');
}
But it's just returning a syntax error, unexpected token if. I'm guessing you can't use if in this way?
return is for passing a value or object out of a function, not blocks like if/else.
var namespace;
if (wgNamespaceNumber == '0') {
namespace = 'Talk';
} else {
namespace = mw.config.get( 'wgCanonicalNamespace' ) + '_talk';
}
You guessed right. You can't assign an IF like that.
Change your code into
var namespace = null;
if (wgNamespaceNumber == '0') {
namespace = 'Talk';
} else {
namespace = (mw.config.get( 'wgCanonicalNamespace' ) + '_talk');
}
And it'll work.
You don't need to return anything. You can just set the value of the variable based on the condition. The function will however need to return a value.
var namespace = (wgNamespaceNumber == '0')
? 'Talk'
: mw.config.get( 'wgCanonicalNamespace' );
The condition above is called a ternary (MDN explains it better)

Categories

Resources