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

The button click event fails to trigger on the first click, but consistently fires on all following clicks

I am currently working on a large-scale asp.net project (fairly new to ASP.NET) and encountering an issue with dynamically added buttons not firing their click events on the first click. The strange part is that this inconsistency occurs; sometimes the but ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Activate fullscreen mode in Krpano on desktop by clicking a button

Is there a way to activate fullscreen mode upon clicking a button? I believe I should use the code: krpano.set(fullscreen,true); Currently, I have an image within a slideshow that includes a play button overlay. Once the button is clicked, the slideshow ...

What is the best location to create the content for a sidebar?

Currently in the process of building my new website using express. The layout consists of various "sections" such as a blog, project information, and more. I want to have a unique sidebar next to the main content for each section. For instance, in the "blo ...

The JSONP ajax call encountered an error, throwing a Uncaught ReferenceError stating that jquery19102754115150310099_1392753827782 is not defined

The code snippet below is from an old version of Knockout jsfiddle, which no longer functions due to being outdated in comparison to current versions of knockout and jquery. This particular fiddle was referenced on the Knockout GitHub wiki recipes link: ht ...

Do we really need to use the eval function in this situation?

Just wondering, is it reasonable to exclude the eval() function from this code? Specifically how <script> ... ... function addGeoJson (geoJsonPath, iconPath = "leaflet-2/images/marker-icon.png", iconSize = [30,50], popUpContent, ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

Identify the class within a child division and include the class in a separate division

How can I detect a special class within a child div and then add a class to another div when that specific class is found? For example: <ul class="m-a-ul"> <li class="menu"> </ul> Now, if the class collapsed is dynamically added: ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

"Experience the latest version of DreamFactory - 2.0.4

I'm encountering a 404 error when I send a request to my new DSP. GET http://example.com/api/v2/sericename/_table/tablename 404 (Not Found) Upon checking the Apache error.log, I found this message: ... Got error: PHP message: REST Exception #404 &g ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. Click here for image description However, we are looking to transition this functionality to an ajax or HTTP call. While w ...

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

Struggling with displaying a PDF file from the local directory in a NextJS application

I've been facing trouble importing and displaying my resume, a local file, within a react component. The code import myResume from '../assets/pdfs/myResume.pdf' is resulting in the error: Error: Cannot find module '../assets/pdfs/myRes ...

The process for changing the textContent to X when an image is clicked

How can I create a function that changes the text content to 'X' when an image is clicked? I already have a function that updates the title based on the image dataset, but combining the two functions has been unsuccessful. Can someone help me con ...

The Infinite Scroll feature is malfunctioning when the $(window).scrollTop() is greater than or equal to $(document).height() - $(window).height() - 10

JavaScript: $.ajax({ type: 'POST', url: 'getcontent.php', data: 'lastid=' + 0, dataType: "html", success: function (data) { console.log(data); $("#content").appe ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

What is the proper location to insert CSS within Laravel?

What is the recommended location for storing CSS or JS files in Laravel? More specifically, what are the differences between placing CSS files in /public versus /resources/css? Which directory is preferable for storing my CSS files? ...

Is there a way to swap out a div with another using ajax and php?

i am looking to update the content from readmore.php into <div id='box'> based on id_pages in index.php after clicking <a class=readmore> Read More </a>. i have been trying to figure out how to retrieve data from readmore.p ...

The Angular 2 Router's navigation functionality seems to be malfunctioning within a service

Currently, I am facing an issue with using Angular2 Router.navigate as it is not functioning as expected. import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Router } from '@angular/ ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...