Only execute function if value is NOT empty [duplicate] - javascript

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 != "" ) {......

Related

How to check on a button click which function was last called out of many custom functions in javascript?

The first method sets the array of objects in the variable final,the second method sets the array of objects in the variable final1.In this particular save method I want to check in the else condition which method was called last(method1 or method2) so that I can decide which variable should I use inside fetchItemId function?
function save(){
if (final === undefined && final1 !== "")
fetchItemId(final1);
if (final1 === undefined && final !== "")
fetchItemId(final);
else {
// I want to call the last executed method out of 2
}
}
You can use a flag variable to check this.
Eg
var i=0;
method1()
{
//whatever
i=1;
}
method2()
{
//whatever
i=2;
}
In your else check value of i.
if(i=1)
// method1 was called last
else
if(i=2)
//method2 was called last
else if (i=0)
// none was called

return false is not working in javascript

I have simple javascript functions which executing a simple string based on some data. Javascript functions i am using are
function checkdata() {
var data = document.getElementById('data').value;
if (data != '') {
console.log("Hello");
return false;
} else {
return true;
}
}
function gotothen() {
console.log("Bye");
}
function changemode(value) {
if (value == 0) {
checkdata();
gotothen();
}
if (value == 1) {
checkdata();
gotothen();
}
}
and the html code i am using are
<input type="text" name="data" id="data">
Hotel
Flight
so if i enter any value to textbox and click on any of the hyperlink it calls changemode() function. there are two function i am calling in changemode() function. One is checkdata() and the other is gotothen(). So if textbox value is not blank then it should not call gotothen() function but it is calling. It should stop after printing "Hello" only but it is calling gotothen() function too after using return false. So how can i stop the execution of gotothen() function if text-box value is not blank ?
It looks like your code is returning false but not actually using that.
You'll want a piece of logic like
if(checkdata()){
gotothen();
}
and you can put it on the outside of your changemode block, like this:
function changemode(value) {
if( checkdata()){
if(value == 0) {
gotothen();
}
if(value == 1) {
gotothen();
}
}
}
because function checkdata has return value, you should capture it for deciding to call gotothen or not.
var check = checkdata();
if (check != false) {
gotothen();
}
or simplify that to:
if (checkdata() != false) gotothen();
and we can simplify again:
if (true_value != false) ...
with:
if (true_value) ...
You are calling gotothen() no matter what. The result from checkdata() doesn't change anything. You don't usr it in the changemode() function, and the changemode function is the one that should eventually return true or false.
You should change your code so that the result from checkdata() is the condition to calling gotothen(). It should be:
if (checkdata())
gotothen();
// ... further execution

Cannot break nested functions in separate functions in Javascript/jQuery

I am trying to add on input method to several dom elements with same class. It is working when the on input function is nested inside the each function. When I try to separate them into two separate functions it doesnt work.
This is the working version
$('.textField').each(function(index, element){
var currentField = $(this);
var currentFieldCheckboxId = "#" + currentField.attr('name')+"Checked1";
// Look for changes in the value
currentField.on('input', function(event){
// If value is NOT empty
if ($.trim(currentField.val()) != '' ) {
// if text fields are unchecked
if (!$(currentFieldCheckboxId).is(":checked")){
$(currentFieldCheckboxId).click();
}
} else {
// If text fields are empty
if ($(currentFieldCheckboxId).is(":checked")){
$(currentFieldCheckboxId).click();
}
}
});
});
NOT working version. It doesnt go into the not empty condition even though .textField isnt empty.
$('.textField').each(function(index, element){
var currentField = $(this);
var currentFieldCheckboxId = "#" + currentField.attr('name')+"Checked1";
// Look for changes in the value
currentField.on('input',qwer(currentFieldCheckboxId,currentField,event));
});
function qwer(currentFieldCheckboxId,currentField,event){
// If value is NOT empty
if ($.trim(currentField.val()) != '' ) {
console.log("not empty field " + currentField.val());
// if text fields are unchecked
if (!$(currentFieldCheckboxId).is(":checked")){
$(currentFieldCheckboxId).click();
}
} else {
console.log("Empty field " + currentField.val());
// If text fields are empty
if ($(currentFieldCheckboxId).is(":checked")){
$(currentFieldCheckboxId).click();
}
}
}
What you want to do is pass a function (a function object, qwer in your case) to another function (the on function). What you are actually doing is calling that function(qwer), and passing the result to another function (and the result is actually undefined, since you return nothing from qwer).
qwer <- that is the function object
qwer(currentFieldCheckboxId,currentField,event) <- that is the result of the function being called
You need to create another function to be called instead, if you want to pass some parameters to qwer.
Try this:
currentField.on('input', function(event) {
qwer(currentFieldCheckboxId, currentField, event);
});

Uncaught TypeError: Cannot read property 'val' of null

I'm new to jquery and I'm getting the error "Uncaught TypeError: Cannot read property 'val' of null" when I try to do the following.
I'm trying to call a function that will check if value of my textbox is null and assign it zero, by calling the id of the function. I know I can assign directly, but there are so many of them, that I feel calling a function is the way to go.
Here's my code for it:
function Fn_Save {
function Fn_NullConvertor(input1) {
if (document.getElementById("input1").val == "") {
document.getElementById("input1").val == 1;
}
}
if (confirm("Save?")) {
Fn_NullConvertor(txtNum_Tracks);
var params = {
Num_Tracks: $.trim($("#txtNum_Tracks").val())
}
}
}
Thanks for your time, I really appreciate it!
There are 5 problems:
The Fn_Save is missing ()
There is no element with input1 id or your code is getting executed before DOM is ready.
There is no .val property for HTMLElement. It is .value
You are using == for assignment
According to what I think, you are after, then
This:
function Fn_NullConvertor(input1) {
if (document.getElementById("input1").val == "") {
document.getElementById("input1").val == 1;
}
}
Should be:
function Fn_NullConvertor(input1) {
if (document.getElementById(input1).value == "") {
document.getElementById(input1).value = "1";
}
}
If input1 is a parameter for an element ID, then you shouldn't have quotes around it. Also note that:
Input elements don't have a val property. The property is called "value".
To assign a value, you need to use the = operator, not ==.
function Fn_NullConvertor(input1) {
var el = document.getElementById(input1);
if (!el) {
throw Error("No element with the ID " + input1 + " was found.");
}
if (!el.value) {
el.value = 1;
}
}
Also, when you pass an ID into your function, the ID should have quotes around it:
Fn_NullConvertor("txtNum_Tracks");
That error means an html element with an id of "input1" cannot be found. You should check that you have something like <input id="input1" type="text"> on your page.
It should be .value since you call pure javascript.
if use jquery it should be .val()

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

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.)

Categories

Resources