When encountering an OR operator, Javascript will cease execution of the remaining conditions

This is a basic JavaScript form-validation I created. All the document.form.*.value references are present on my page, except for the document.form.dasdasdas.value ==''.

In the code below, the purpose is to display an error if any of the forms are left empty. However, since dasdasdas is not a valid form on my page, no error occurs. My question is why.

If it doesn't exist, shouldn't it be considered empty?

I noticed that even after filling in all the fields (customername to customerpostcode) and leaving customerbank and customercity empty, it still indicates that everything is okay.

Upon removing that line, everything functions properly. But I am intrigued by why it behaves this way!

Your response to this somewhat murky explanation would be much appreciated!

Here is the code I am referring to:

function FileChecked()
{
    if( document.form.customername.value =='' || 
        document.form.customerpassword.value =='' || 
        document.form.customerphone.value =='' || 
        document.form.customeremail.value =='' || 
        document.form.customeradres.value =='' || 
        document.form.customerpostcode.value =='' ||
        document.form.dasdasdas.value =='' || 
        document.form.customerbank.value =='' || 
        document.form.customercity.value =='')
            {
                alert('Not all forms are filled.');
                return false;
            }
    // Check if file is selected and has a .csv extension
    if(document.form.csvfile.value =='')
        {
            alert('No file given');
            return false;
        }
    else
        {
        ext = document.form.csvfile.value.toLowerCase();
        if(ext.substr(ext.length-4) == '.csv')
            {
            return true;
            }
        else
            {
            alert ('Filetype is not .csv');
            return false;
            }           
        }
}

Answer №1

If the element document.form.dasdasdas is not present, it will be considered as undefined. Attempting to access the property value of an undefined element will result in an error.

To handle this situation, you can use a conditional check like:

... || (document.form.dasdasdas === undefined || document.form.dasdasdas.value == '') || ...

However, keep in mind that if document.form.dasdasdas does not exist in the DOM, filling it in will be challenging for users.

Answer №2

When attempting to access the value property of an element, it is necessary for the element to actually exist on the page or within the DOM itself.

document.form.dasdasdas

It appears that in this case, you are trying to retrieve the value of a non-existent element. When you attempt to access its value property, it returns undefined.

To prevent this, it is advisable to first check if the element is undefined before attempting to access its value and perform your comparison.

(document.form.dasdasdas != undefined || document.form.dasdasdas.value == '')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it best to stick with a static page size, or

While I typically design my webpages dynamically by determining the screen size and creating divs accordingly, I'm curious about the advantages of using a 'static' sizing approach (such as using pixels). Any insights on this contrasting meth ...

Handling a substantial array containing over 12,000 rows in JavaScript

The criteria for this project are unique, but I am seeking some perspective... I possess a CSV file filled with 12,000 rows of data distributed across 12-15 columns. My objective is to convert this into a JSON array and load it using JSONP (must be execut ...

What is the process for importing extensions and files in Visual Studio Code?

Nodejs development utilizing (--experimental-modules) Current visual studio code intelligence import example: import config from "./config"; However, it should be imported as: import config from "./config.js"; An error is encountered without the . ...

Having difficulty retrieving the current time of an audio element using jQuery

Currently, I am facing an issue while attempting to manage an audio element for my custom player. Despite numerous attempts, I have been unsuccessful in acquiring the currentTime and duration properties. Below is a snippet of what I've tried: var pla ...

Ways to determine if the popupState component in Material UI is currently opened

I am currently utilizing PopupState and the Popover component to create a specific element. It is functioning properly, but I have a requirement to modify the icon displayed based on whether the popup is open or closed. Here is the code for my component: ...

The alert box fails to display in the correct orientation when the condition is activated

Currently, I am working on implementing a sign-up feature using PHP. My main goal is to successfully store the user-entered data in MySQL database while ensuring that no duplicate usernames are allowed during account creation. Although everything is functi ...

Is it achievable to animate dynamic height using CSS? Open to JS alternatives as well

I am currently utilizing AngularJS, which enables me to utilize ng-show and ng-hide in order to display or hide elements based on a logical condition. My goal is to animate the size changes of the container when the child objects are shown or hidden, creat ...

Encountered an issue with the Mongoose Schema method: The model method is not recognized as a

Here are two Mongoose model schemas that I am working with. The LabReport model includes an array that references the SoilLab model. Within the SoilLab model, there is a static method that was initially used to choose which fields to display when retrievin ...

Using redux alongside fela and react: A comprehensive guide

First of all, thank you for your attention. I am currently exploring the use of fela for dynamically styling my components and for managing app states, I plan to incorporate redux. In fela, it's necessary to utilize a Provider to encompass all app com ...

Using node.js to make an HTTP request and parse JSON data with the

I am currently working on developing a web application using node.js that needs to interact with a PHP API. My goal is to request a JSON object from the PHP API, which I can then use in one of my .ejs templates. Below is the code snippet for my node.js im ...

Issue with Select2: When using a remote select2 control, the tab key press does not allow for the selection of the highlighted

I have set up select2 to load ajax data into select2 based on the example provided in this link Load ajax data into select2. In the example, I can type text, use arrow keys to navigate, and then hit tab to select the highlighted item. However, in my case, ...

Utilizing conditional statements like if/else and for loops within a switch statement in JavaScript allows for

I am currently developing a request portal that involves dynamic checkboxes, labels, and textboxes that are dependent on an option list. As a beginner in javascript, I am facing challenges with creating conditional statements. I have managed to make progr ...

Using Node.js and Less to dynamically select a stylesheet source depending on the subdomain

Currently, my tech stack consists of nodejs, express, jade, and less. I have set up routing to different subdomains (for example: college1.domain.com, college2.domain.com). Each college has its own unique stylesheet. I am looking for a way to selectively ...

Is Kendo Telerik grid capable of applying conditional formatting while filtering?

Is it feasible to modify the background color of rows in a Kendo Telerik grid when a filter is implemented within an ASP.NET MVC application? ...

Reading values from a properties file using HTML

Here's a snippet of my HTML code: First name: <input type = "text" > Last name: <input type = "text"> Instead of manually inputting the field values (First name, Last name) in the HTML, I am interested in reading them ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

Typescript throws an error indicating that the "this" object in Vue methods may be undefined, displaying error code TS2532

As a beginner in question writing, I apologize if my wording is not clear. The issue at hand: I am working on a Vue application with TypeScript. export default { methods: { setProgram: (program: Program)=>{ this.program = progra ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

What are the steps to implement timer control in Ajax using JavaScript?

Hello, I have been trying to establish communication with the server through my application. To achieve this, I made a call to the webservice using AJAX. Now, I am looking to incorporate a time interval in AJAX. Can anyone kindly provide guidance on how ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...