An error is triggered when attempting to target multiple element Id's in Javascript and one of them cannot be located

I have encountered an issue when trying to target multiple IDs with JavaScript in order to disable input fields associated with them. The script I am using seems straightforward, but I noticed that on pages where the middle element is missing, the third one does not get disabled (it appears as though the script stops working if the second element is not found).

<script>
document.getElementById("id_1").disabled = true;
document.getElementById("id_2").disabled = true;
document.getElementById("id_3").disabled = true;
</script>

On pages where all three IDs are present, the script functions correctly. However, on pages where either "id_1" or "id_2" is absent, the remaining elements are not disabled even if they exist.

Is there a workaround for this issue? Please note that creating separate scripts for each page is not feasible, as this code will be placed in the footer, which is consistent across all pages.

Thank you!

Answer №1

To ensure proper functionality, it is advisable to check for the existence of an element before disabling it. Additionally, storing the ids in an array can help simplify the code structure.

var ids = ['id_1','id_2','id_3'];

for (var i = 0; i < ids.length; i++) {
  var el = document.getElementById(ids[i]);
  el && (el.disabled = true);
}
<input id="id_1" value="id_1">
<input id="id_3" value="id_3">

Answer №2

The reason for this issue is that the document.getElementById function will return null if it cannot find the specified element in the DOM. This results in an exception being thrown when you try to set the disabled attribute on a null value. To avoid this error, you need to verify that the element has been located successfully before attempting to modify it, or iterate through all elements to ensure they are present.

Answer №3

Summary:

The main issue causing the script to stop functioning is an error triggered when attempting to disable a non-existent element.

Exploration:

When using document.getElementById(), if the specified element does not exist, it will return null (Refer to MDN for more details).

If you try to apply true to the .disabled property of null, JavaScript will raise a TypeError. If this error is not addressed with a try/catch block, the script will halt execution and subsequent input elements will not be disabled.

Resolution

To rectify this issue, verify that the target element actually exists before setting it as disabled. Consider implementing the following approach:

var el = document.getElementById('id_1');

if ('null' !== typeof el) {
  el.disabled = true;
}

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

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Is it possible to apply the onbeforeunload event exclusively for when the site is being redirected to a specific website?

Is there a way to selectively apply onbeforeunload when a site is redirecting to a specific page? ...

Disable ESLint's "no-undef" rule for a specific folder when using Jest

Currently, I am using jest for testing my api calls. In addition, I utilize eslint to validate my test codes. However, since jest does not require explicit definition of methods such as test() or expect(), when running eslint, I encounter errors like: ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

Building a responsive image gallery modal using AJAX in Laravel platform

How can I fix the issue of the modal content briefly appearing when I load my page? I am trying to create an image gallery where a modal opens when an image is clicked. Here is the code in my view.blade.php: <script> $(".li-img").click(function ( ...

Unable to transfer a function to a component using <Route /> tag

In the Erm component, the function setErm is undefined even though it is received by the App component. When passing something like something='foo', the ERM component receives it but not setErm={props.setErm} const App = props => { console. ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

It's important to understand how to correctly send state values from a parent component to a child component

I have a tab menu in my code and I am looking to implement a feature where tabs can be switched using a button. The challenge is passing the values of these tabs into the onclick function of the button in order to navigate between them. Here is an example ...

The AJAX call fails to refresh the secondary table in CodeIgniter

I have a situation where I need to display data from two tables - car producer and car model, pulled from a database. My goal is to filter the second table to only show cars from a specific producer when that producer is clicked in the first table. I attem ...

React failing to refresh in browser following compiler error when saved

Recently starting to work with React, I have observed an interesting behavior. When I create my app using create-react-app, it automatically updates when I save it in VSCode, which is normal. However, I have noticed that as soon as I encounter my first c ...

Angular directive for dynamic template inclusion

I am facing an issue while creating a directive that should automatically add tabs and their content. The problem I'm encountering is retrieving the content stored in partials/tabs/tab[x].html. In my code, I have defined a constant named AvailableTab ...

Creating a circle in SVG that cannot be scaled using Javascript

I'm working on a map project using JavaScript and SVG for drawing the lines. One feature I'd like to implement is the ability to search for a specific road, and if found, display a circle on the map. I understand how to draw a circle in SVG, bu ...

Struggling to display a function's output on a separate web page within a flask application

After spending close to 10 hours on this, I find myself stuck. My restaurant search app is functioning perfectly when I print the output to the terminal. However, I can't seem to figure out how to display it on a new page. Here's a snippet of my ...

Loop through the mongoose object using EJS

When I insert <%= products %> into my view, it displays [Object Object], indicating that the mongoose resultset is an object. However, when I attempt to iterate over the products object, I receive an error stating products.forEach is not a function. ...

How to properly format the <address> element on my website to display our company's contact information

While developing a website with asp.net mvc-5, it's important to include our company's contact details like telephone, email, and postal address. That's why I utilized the <address> tag within our "Contact US" page, replacing actual in ...

Text that is curving around a D3.js pie chart

I am currently working on creating a 3D-Js chart and I would like the pie text to wrap around the pie itself. This is the exact effect that I am trying to achieve: https://i.sstatic.net/YOLdo.png I am facing two main issues: I am currently printi ...

What is the best location in my redux store to store my socket connection?

As a beginner in the world of Redux, I've been using slices and redux-thunks to manage my redux store. However, I've come to realize that storing my socket connection in the state is not ideal. This connection is critical across multiple componen ...

Combining two divs to share the same linear gradient and shadow effect

Greetings to all our valued partners! I am seeking guidance on how to achieve the following task for a web application I am developing: Within my webapp, I have designed a stylish NavBar similar to the examples depicted in the images (in AdobeXD it is di ...

JavaScript parsing error occurred

Encountering a parsing error in my JavaScript code when deploying Firebase functions. The error mentions an unexpected token, indicating there might be a character out of place. I've been stuck on this issue for weeks now. Any assistance would be grea ...

Angular for user authentication page

I've been busy working on the login page, and I've managed to create a login UI that meets the requirements. However, I'm facing some challenges when it comes to validating the username and password. Being new to Angular and Web API, I might ...