There was an error message saying "Unable to locate property 'getElementById' in undefined"

I am facing an issue with a jQuery filter function, and the error message it's showing is:

Cannot read property 'getElementById' of undefined

 function CheckFilter() { 
    var input, filter, table, tr, td, i, searchFilter;
    input = document.getElementById("searchInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("dataTable");
    tr = table.getElementsByTagName("tr");
    searchFilter = document.getElementById("filterSearch").value;
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[searchFilter];
        var productType = tr[i].getElementById("productType").value;
        if (td) {
            if (productType == $('#Products').prop("checked")) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

Below is the HTML structure of my table and checkbox. The objective is to display rows based on the checked status of the checkbox in relation to the typeProduct field.

 <div class="form-group">
                    <div class="col-sm-3">
                        <select id="filterSearch" class="form-control">
                            <option value="0">Code</option>
                            <option value="1">Description</option>
                        </select>
                    </div>
                    <div class="col-sm-7">
                        <input type="text" id="searchInput" placeholder="Search.." onkeyup="checkFilter();" class="form-control" />
                    </div>
                </div>
                <div class="modal-body">
                    <div class="table-overflow col-sm-12">
                        <table class="table table-responsive table-hover" id="dataTable">
                            <thead>
                                <tr>
                                    <th>Code</th>
                                    <th>Name</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var item in Model.Product)
                                {
                                <tr>
                                    <td>@item.Code</td>
                                    <td>@item.name</td>
                                    <td align="right">
                                        <a href="#" onclick="closeModal();LoadProduct('@item.Code');" title="Select"><i class="fa fa-check-circle fa-lg"></i></a>&nbsp;
                                    </td>
                                    <td id="productType" value="@item.ProductType">@item.ProductType</td>
                                </tr>
                                }

                            </tbody>
                        </table>
                    </div>
                </div>

<input type="checkbox" asp-for="Products" onclick="checkProduct();" name="Products" id="Products"/>

Answer №1

When using getElementById, remember it is accessible on the document object, not on individual <code>tr
elements.

Check out the documentation for more information.

If you are dealing with multiple elements sharing the same id within a table, consider revising your approach to avoid potential conflicts. Share your HTML code and intended outcome for personalized assistance.

UPDATE:

Upon further investigation, it appears that the td elements are repeating in a loop, resulting in multiple instances of the same id. The recommendation here would be to remove the id attribute from these elements.

To access the desired value located in the last td, you could use this method as one solution:

td[td.length-1].innerHTML

Revise your loop implementation accordingly:

for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[filtro];

        if (td) {
            var tipoProduto = td[td.length-1].innerHtml;

            if (tipoProduto == $('#Produtos').prop("checked")) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }

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

Using JSP and Jquery for uploading files

I have a specific requirement to submit a form asynchronously using AJAX, which includes a file input. Below is the code I have written, however, I am encountering an error. Input.jsp: <script> function fileUpload() { var formData = $('#myform ...

Modify the border in jQuery if a specific div exists within a list item

Here is a collection of items: <div class="wine"> <H1>Title</H1> <div class="promotion"></div></div> <div class="wine"> <H1>Title</H1> </div></div> <div class="wine"> <H1>Title& ...

How can Vue.js transfer form data values (using v-model) from a Parent component to a Child component?

I am working on a multistep form using vue.js. The parent form collects two inputs and once these are validated, it moves to the next step which involves a child component. I want to pass the values from the parent component to the child component's f ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { i ...

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this: { "soils": [{ "mukey": "658854", "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)", "sl_source": "Fl soil map", "cokey": "3035468", "soilName": "Eunola", " ...

Can someone provide instructions on how to convert base64 data to an image file

I'm utilizing the vue-signature Library but I am unsure how to download the base64 data that is generated as an image. Here is the link to the library: https://www.npmjs.com/package/vue-signature. I have gone through the documentation and noticed that ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

Enhance the clarity of content within an IFrame by sharpening the focus on

I recently developed an iframe to open a chat site I built using React.js and Tailwind. The iframe is loaded dynamically on the website through javascript. However, I noticed that when I click on the input field inside the iframe, the content appears blurr ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

What makes this lambda function in TypeScript successfully execute without any errors?

I was under the impression that this code let x: (a: { b: number }) => void = (a: { b: number, c: string }) => { alert(a.c) }; x({ b: 123 }); would result in an error because the lambda function requires an additional property on the a argument, m ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

Angular JS encountered an issue with executing 'removeChild' on 'Node' for HTMLScriptElement.callback, leading to an uncaught DOMException

I am currently using Angular's JSON HTTP call. When making a post request, I experience an error during runtime: Uncaught TypeError: Cannot read property 'parentElement' of undefined at checklistFunc (masterlowerlibs.67785a6….js:42972 ...

How can you implement a repeating carousel with JavaScript?

I recently came across some carousels on and was intrigued by how they smoothly repeat the slides. Instead of jumping back to the first slide when reaching the end, it seamlessly transitions from the final slide back to the first one. I am eager to learn ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

JavaScript function using recursion returning an undefined value

I have created a function that generates a random number and checks if it already exists in an array. If it does, the function generates a new number until a unique one is found and adds it to the array. However, I am encountering an issue where the functi ...