refreshing the table with data that has been refined

Here is the code snippet provided.

I have successfully developed a filter to clear a table and retrieve data based on user-specified last name criteria. However, I am struggling with repopulating the table with the filtered results.

Possible issues include:

-RegExp: As a newcomer to RegExp in JavaScript, I believe the syntax is correct but I require confirmation. Additionally, I am uncertain if I can utilize it as intended (setting it:

filterCriteria = new RegExp("^" + filter.value)
and then checking if the last_name object matches it:
if (contacts.last_name  === filterCriteria)
)

  • Even assuming the RegExp functions correctly, can I create a new array based on it within that If statement? In other words, does it suffice to say, "Select only objects with a last name matching the criteria and move them into a new array"?

Thank you for your assistance!

var filter = document.getElementById("filter");
    filter.addEventListener("keydown", function (event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            if ((xhr.readyState === 4) && (xhr.status === 200)) {
                var contacts = JSON.parse(xhr.responseText).data,
                    filterCriteria = new RegExp("^" + filter.value),
                    i;
                for (i = 0; i < contacts.length; i += 1) {
                    var contactTableBody = document.getElementById("contactTable").lastElementChild,
                        lastRow = contactTableBody.lastElementChild;
                    contactTableBody.removeChild(lastRow);
                }
                if (contacts.last_name  === filterCriteria) {
                    var filterResults = [contacts];
                    for (i = 0; i < contacts.length; i += 1) {
                        contactTableBody = document.getElementById("contactTable").lastElementChild;
                        var newRow = [],
                            newNameCell = document.createElement("td"),
                            newPhoneCell = document.createElement("td"),
                            newEmailCell = document.createElement("td"),
                            newNameNode = document.createTextNode(contacts[i].last_name + ", " + contacts[i].first_name),
                            newPhoneNode = document.createTextNode(contacts[i].phone),
                            newEmailNode = document.createTextNode(contacts[i].email);

                        newRow[i] = document.createElement("tr");
                        newRow[i].id = "contact" + i;
                        newNameCell.appendChild(newNameNode);
                        newPhoneCell.appendChild(newPhoneNode);
                        newEmailCell.appendChild(newEmailNode);
                        newRow[i].appendChild(newNameCell);
                        newRow[i].appendChild(newPhoneCell);
                        newRow[i].appendChild(newEmailCell);
                        contactTableBody.appendChild(newRow[i]);
                    }
                }
            }

UPDATE:

While unsure about the brace/bracket notation, this should provide insight into the data structure.

contacts = JSON.parse(XMLHttpResponse.responseText).data  = { [
    { "first_name":"Jim", "last_name":"Cooper", "phone":"8435555555", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0506022f070e031f0a1d1b410c0002">[email protected]</a>" },
    { "first_name":"Jim", "last_name":"Aaron", "phone":"1234567890", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="264c4f4b664443474b0845494b">[email protected]</a>" },
    { "first_name":"Mark", "last_name":"Smith", "phone":"4567891236", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bed3dfcd5fecdd3d7cad690ddd1d3">[email protected]</a>" },
    { "first_name":"Sally", "last_name":"Smith", "phone":"5469876622", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5c4e4343566f5c42465b47014c4042">[email protected]</a>" },
    { "first_name":"Mary", "last_name":"Coppersmith", "phone":"6854895212", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be6eaf9f2cbe8e4fbfbeef9f8e6e2ffe3a5e8e4e6">[email protected]</a>" }        
] }

Answer №1

Santosh originally mentioned:

Although I don't have the full context, shouldn't the contacts.last_name be placed inside the for loop? Perhaps something like

contacts[i].last_name == filterCriteria
. Providing mock data for contacts or a JSFiddle would be beneficial.

It turns out that a for loop was indeed necessary. Thank you for pointing that out.

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

Retrieving JSONObject in Android

My JSON data is structured as follows: { "id": "11111", "title": "Title", "url": "www.example.com", "fulltext": { "page1": "<p>balblabba</p>", "page2": "<p>avavaava</p>" }, "related_articles": [ { "id" ...

How can I restrict the number of input data to 10 on a single page in a TodoList application?

As a newcomer to web development, I recently built a todoList app. It's functioning flawlessly and allows me to add multiple lists to my webpage with ease. The technologies used are React js and Bootstrap. However, I now wish to implement a limitati ...

Is it possible to include text in my numbered list?

My itinerary consists of the following ordered list: place1 place2 place3 Since this is for a trip plan, I would like it to appear as follows: Day 1: place1 Day 2: place2 Day 3: place3 I could manually type it out as plain text, but I am looking for ...

The Datepicker in MUI - React is unable to recognize the `renderInput` prop on a DOM element

I've been experimenting with the MUI version 5 DatePicker component. I followed the example provided in the MUI documentation's codesandbox demo. Here is how my component looks: const MonthPicker: FC = () => { const [value, setValue] = Rea ...

Guide on utilizing popup box input to amend CSS (background color)

I'm looking for some guidance on JavaScript and CSS. Is there a way to create a popup box where users can input a color (any main primary color recognized by CSS) and then have the background color of the page change accordingly in an external styles ...

In order to achieve dynamic Static Site Generation (SSG), it is essential to

I'm a beginner with Next.js and have been experimenting with using getStaticProps in the dynamic pages of my Next.js application. However, I keep encountering the following error: Error: getStaticPaths is required for dynamic SSG pages and is missin ...

What is the efficacy of utilizing temporary variables rather than constantly referencing the full values?

Consider an object structured as follows: var foo = { a: { b: { c: { d: { e: { f: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] } } } } } }; We have functions that use different parts of this object like so: function doStuff() { if ( foo.a.b.c.d.e.f[ 5 ] >= s ...

Displaying an image in AngularJS using a byte array received in the response

Dealing with a service that adds properties to a file and returns it as a byte array in the response. I'm struggling to display it properly since it's in byte form. Attempted converting it to base64 but still showing raw bytes. PNG IHDR&L ...

Utilizing RxJs operators in Angular: utilizing async pipe and tap does not fill data

Here is a code snippet I've been working on: This snippet is written in Typescript: isDataSearch = false; getDatacollectionByID() { const params = { id: <some random ID>, }; this.metaData = this.dataService.getDatacollectionByID(par ...

Accessing Facebook through Iframe Redirect

I am currently developing a Facebook IFrame App and have implemented the following javascript code to prompt users to log in and grant necessary permissions for the application. Once they do this, they should be redirected to the iframe app successfully. T ...

Vue 3: Leveraging Functions Within Mutations.js in Vuex Store to Enhance Functionality

In my mutations.js file, I have encountered a situation where one function is calling another function within the same file. Here's an example of my code: export default { async addQuestionAnswer(state, payload) { alert(payload); this.update ...

Is it necessary for me to use a .jsx extension when saving my React component files?

After working with React for a few months, I recently noticed that some of my files have the .js extension while others have the .jsx extension. Surprisingly, when I write JSX code in the .js files, everything still functions correctly. Is there any signif ...

What is the best way to toggle between different sections of a webpage using HTML, CSS, and Javascript?

I am looking to display unique content based on the user's selection of different month/year options on the same page. For example, if the user chooses March 2021, I would like to show them events specific to that month. Here is a screenshot for refer ...

How to Deserialize JSON with numerical keys using Json.NET

Is there a way to convert the provided JSON data into an object using Json.NET? The issue I am facing is that the class name must start with a number. One example of such a scenario is when using the Wikipedia article API. By making a request through the ...

Could not locate org.jose4j.json.internal.json_simple module

After setting up my Android project and adding an external JAR in IntelliJ, I installed "json-simple-1.1.jar" to access the package org.jose4j.json.internal.json_simple. I made sure to configure the library settings from the project structure menu. Howeve ...

Switch the Aloha-Editor language option

I'm looking to incorporate the Aloha-Editor into one of my projects. The default language for this project is German, but I haven't been able to find a way to switch the editor's language. (I've searched online and through their website ...

What steps can I take to modify the peeking effect from hover to scrolling?

I have successfully integrated a peeking effect on my website. Check it out here: http://jsfiddle.net/7yrWL/1/ Currently, the effect triggers when I hover over the image. What I want now is for the peeking effect to only activate when the user scrolls to t ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

The useEffect hook is failing to trigger within the Higher Order Component (Hoc

My component was working fine without using a HOC, but now that I've wrapped it inside withSpinner HOC, the fetching process does not start. const CollectionPage = (props) => { const { isCollectionLoaded, isCollectionFetching } = props; useEf ...

Guide on extracting the keys from an object_construct and displaying them in their own distinct column

My data is structured in a table format. Here is an example: ID ALL_ATTRIBUTES ALL_FIELDS 1 {"name" : "JESSICA"} {"name"} 2 {"age": 15, "name": "JOSH"} {"age", "name" ...