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

Can CSS be used to separate elements within a div from the overall page styles, similar to how an iFrame functions?

Is there a way to isolate elements within a div, similar to how it would behave in an iFrame? I am facing issues with the global SharePoint styles affecting my app inside SharePoint. I want to completely disable these global styles so that my app only use ...

I require assistance in displaying a dynamic, multi-level nested object in HTML using AngularJS

I have a complex dynamic object and I need to extract all keys in a nested ul li format using AngularJS. The object looks like this: [{"key":"campaign_1","values":[{"key":"Furniture","values":[{"key":"Gene Hale","values":[{}],"rowLevel":2},{"key":"Ruben A ...

Utilizing Vue's data variables to effectively link with methods and offer seamless functionality

I am encountering difficulty retrieving values from methods and parsing them to provide. How can I address this issue? methods: { onClickCategory: (value) => { return (this.catId = value); }, }, provide() { return { categor ...

Attempting to send a GET request from localhost:8080 to localhost:3000 is proving to be a challenge as I keep encountering a CORS error. Even after trying to install CORS on my node.js server, the issue

While attempting to send an axios GET request from my front-end app on localhost:8080 to my Node.js/Express.js server on localhost:3000, I encountered a CORS error. Despite installing the cors npm package and using it as middleware in my Node.js/Express.js ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

What is the best way to convert a locale code into a language name with i18next?

In the application I'm working on, there is a language selector feature that allows users to choose the display language for the app. Currently, we only have limited options available, but there are plans to expand the list in the future. My goal is t ...

Exploitable Weakness Found in NestJS Version 8.4.5

After running npm audit on my npm package recently, I encountered an error that is related to the dicer package, widely used by NestJS. I have looked for solutions online but haven't been able to find any fixes so far. Has anyone else managed to reso ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

Vue.js Dynamic Class Binding Fails to Update

As I delve into learning Vue Js, I have been working on a simple todo app. One interesting thing I've done is binding a class to my todo items based on whether todo.completed is true or not: <a v-bind:class="{iscomplete : todo.completed}& ...

Utilizing jQuery show() and hide() methods for form validation

I created a form to collect user details and attempted to validate it using the jQuery hide and show method. However, I seem to be making a mistake as the required functionality is not working correctly. What am I missing? I have searched for solutions on ...

What is the correct way to send an HTTP error code to an error handling middleware?

Currently, I am in the process of developing a RESTful API using node.js and express framework. I would like to create a single error handling middleware for this project. The approach I am currently considering involves: router.get('/some-resource&a ...

Having trouble with $(document).ready not functioning correctly?

After following the instructions to move my jQuery CDN to the bottom of the page, I encountered a problem. The script below was functioning perfectly when my jquery files were at the top of the page: if ($(window).width() >= 768) { $('.col-l ...

The file import is restricted based on the user's input

I am facing an issue with my small vue.js app. My goal is to import a specific json file based on user input. import content from "@/posts/posts/" + new URL(location.href).searchParams.get('id') + ".json"; Every time I attem ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

Analyzing the DOM content loading time for web pages generated using AJAX technology

When analyzing website performance, I rely on window.performance.timing. However, this method falls short when it comes to measuring the performance of webpages loaded through ajax calls. For instance, websites built with frameworks like angularjs often lo ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

pretending to make an ajax call using jQuery

To enhance the user experience of file upload, I have implemented a fake ajax request. When the user clicks submit, the form disappears, a loading graphic appears, and after a few seconds, the page refreshes to display the newly uploaded image. However, e ...

I successfully managed to ensure that the splash screen is only displayed upon the initial page load. However, I am now encountering an issue where it fails to load again after I close the page. Is there any possible solution

After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...

Can someone explain why I can't find yarn dlx? And can you please provide instructions on how to run the yarn

After installing yarn with brew install yarn, I attempted to run yarn dlx storybook@latest upgrade. However, the result showed an error: yarn run v1.22.22 error Command "dlx" not found. info Visit https://yarnpkg.com/en It seems that commands like yarn ad ...