Use Javascript to search for phone data within the object and showcase it in a table

When a key is pressed in an input field, JavaScript retrieves data from a JSON object and displays it in an HTML table.
I require assistance with:

1: Sort the data by phone number and only display the table row that contains numbers from the input, hiding all others.

2: Clicking on a table row should open a modal where additional data {"card_number": "1234 1234 4444 5555","anydata": " something ","anydata2": "hello"} from res corresponding to this phone number object will be shown.

Below is my code:

function SearchPhone() {
  var phone = $('#phonesearch').val();
  var res = {
    "2": {
      "name": "Sardor",
      "surname": "Aliev",
      "patronym": "Begmatovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "2",
      "phone": "85673454534",
      "card_number": "1234 1234 4444 5555",
      "anydata": " something ",
      "anydata2": "hello"

    },
    "3": {
      "name": "Akbar",
      "surname": "Valiev",
      "patronym": "Sharipovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "2",
      "phone": "85672312335",
      "card_number": "1234 6543 4444 5555",
      "anydata": " something ",
      "anydata2": "hello"
    },
    "4": {
      "name": "Mansur",
      "surname": "Bakirov",
      "patronym": "Maksutovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "1",
      "phone": "85657652311",
      "card_number": "1234 6543 1111 5535",
      "anydata": " something ",
      "anydata2": "hello"
    },
    "5": {
      "name": "Xamid",
      "surname": "Saliev",
      "patronym": "Aripovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "4",
      "phone": "85672115535",
      "card_number": "1234 2353 5444 2345",
      "anydata": " something ",
      "anydata2": "hello"
    },
    "6": {
      "name": "Bobur",
      "surname": "Qobilov",
      "patronym": "Axmetovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "3",
      "phone": "85672612664",
      "card_number": "1287 3853 4734 5475",
      "anydata": " something ",
      "anydata2": "hello"
    }
  };
  var sttr = '<tr class="" style="cursor: pointer;" data-toggle="modal" data-target="#myModal1"><th  scope="row" id="listnum_fp">';
  endtr = '</tr>';
  stth = '<th style="white-space: nowrap">';
  endth = '</th>';
  sttd = '<td style="white-space: nowrap">';
  endtd = '</td>';
  for (const key in res) {

    var f_i_sh = stth + res[key].surname + ' ' + res[key].name + ' ' + res[key].patronym + '' + endth;
    publicated = sttd + res[key].date_pub + endtd;
    willget = sttd + res[key].date_get + endtd;
    status = sttd + res[key].status + endtd;
    phone = sttd + res[key].phone + endtd;
    datarowout = sttr + (key - 1) + f_i_sh + publicated + willget + status + phone + endtr;
    document.getElementById('cardmod_fp').innerHTML += datarowout;

  }
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive">
  <table class="table table-lg table-bordered shadow bg-light ">
    <thead>
      <tr>
        <div class="card-header text-right">
          <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-3"></div>
            <div class="col-md-3"></div>
            <div class="col-md-3">
              Phone input: <input id="phonesearch" onkeyup="SearchPhone()" type="text" class="form-control">
            </div>
          </div>

        </div>

        <tr>
          <th style="width: 40px;" scope="col">№</th>
          <th scope="col">Name</th>
          <th scope="col">Post Date</th>
          <th scope="col">Get Date</th>
          <th scope="col">Status</th>
          <th scope="col">Phone number</th>
        </tr>
    </thead>

    <tbody id="cardmod_fp">

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


<div class="modal resizable draggable fade" data-backdrop="false" id="myModal1" role="dialog">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content rounded-0 shadow-lg">
      <div class="modal-header bg-light">
        <button type="button" class="close" data-dismiss="modal">&times;</button>

      </div>
      <div class="modal-body">
        <p class="moredata"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-refuse " data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-default " data-dismiss="modal">Send</button>
      </div>
    </div>
  </div>
</div>

Answer №1

To start off, move the 'res' variable outside of the search function and then clear the input field

Here is an updated version that should work properly.

var res = {
  "2": {
    "name": "Sardor",
    "surname": "Aliev",
    "patronym": "Begmatovich",
    "date_pub": "12.02.2019",
    "date_get": "12.03.2019",
    "status": "2",
    "phone": "85673454534",
    "card_number": "1234 1234 4444 5555",
    "anydata": " something ",
    "anydata2": "hello"

  },
  "3": {
    "name": "Akbar",
    "surname": "Valiev",
    "patronym": "Sharipovich",
    "date_pub": "12.02.2019",
    "date_get": "12.03.2019",
    "status": "2",
    "phone": "85672312335",
    "card_number": "1234 6543 4444 5555",
    "anydata": " something ",
    "anydata2": "hello"
  } // more entries
};

function SearchPhone() {
  var phone = $('#phonesearch').val();
  document.getElementById('cardmod_fp').innerHTML = ""
  var sttr = '<tr class="" style="cursor: pointer;" data-toggle="modal" data-target="#myModal1"><th  scope="row" id="listnum_fp">';
  endtr = '</tr>';
  stth = '<th style="white-space: nowrap">';
  endth = '</th>';
  sttd = '<td style="white-space: nowrap">';
  endtd = '</td>';
  for (const key in res) {
    if (phone === "" || res[key].phone.indexOf(phone) === 0) {
      var f_i_sh = stth + res[key].surname + ' ' + res[key].name + ' ' + res[key].patronym + '' + endth;
      publicated = sttd + res[key].date_pub + endtd;
      willget = sttd + res[key].date_get + endtd;
      status = sttd + res[key].status + endtd;
      phoneCell = sttd + res[key].phone + endtd;
      datarowout = sttr + (key - 1) + f_i_sh + publicated + willget + status + phoneCell + endtr;
      document.getElementById('cardmod_fp').innerHTML += datarowout;
    }
  }
}
SearchPhone()
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive">
  <table class="table table-lg table-bordered shadow bg-light ">
    <thead>
      <tr>
        <div class="card-header text-right">
          <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-3"></div>
            <div class="col-md-3"></div>
            <div class="col-md-3">
              Phone input: <input id="phonesearch" oninput="SearchPhone()" type="text" class="form-chttps://stackoverflow.com/questions/59200666/javascript-search-by-phone-data-through-the-object-and-display-in-the-table#ontrol" value="">
            </div>
          </div>

        </div>

        <tr>
          <th style="width: 40px;" scope="col">№</th>
          <th scope="col">Name</th>
          <th scope="col">Post Date</th>
          <th scope="col">Get Date</th>
          <th scope="col">Status</th>
          <th scope="col">Phone number</th>
        </tr>
    </thead>

    <tbody id="cardmod_fp">

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


<div class="modal resizable draggable fade" data-backdrop="false" id="myModal1" role="dialog">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content rounded-0 shadow-lg">
      <div class="modal-header bg-light">
        <button type="button" class="close" data-dismiss="modal">&times;</button>

      </div>
      <div class="modal-body">
        <p class="moredata"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-refuse " data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-default " data-dismiss="modal">Send</button>
      </div>
    </div>
  </div>
</div>

Answer №2

I've made some necessary adjustments to your code, along with improved guidelines (though not exhaustive), and added comments where needed for better clarity.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

   // Function to filter out required phone numbers
   function filter(phoneNumber, data){

    // Return all data if no search string is provided
    if(phoneNumber == "" || phoneNumber == undefined || phoneNumber == null){
        return data;
    }

    let resultData = {}
     for(var key in data){
         let personData = data[key]
        if(personData.phone.indexOf(phoneNumber) >= 0){
            resultData[key] = personData;
        }
     }

     return resultData;
   }
  
function getAllPhoneNumbers(){
    var res = {
    "2": {
      "name": "Sardor",
      "surname": "Aliev",
      "patronym": "Begmatovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "2",
      "phone": "85673454534",
      "card_number": "1234 1234 4444 5555",
      "anydata": " something ",
      "anydata2": "hello"

    },
    "3": {
      "name": "Akbar",
      "surname": "Valiev",
      "patronym": "Sharipovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "2",
      "phone": "85672312335",
      "card_number": "1234 6543 4444 5555",
      "anydata": " something ",
      "anydata2": "hello"
    },
    "4": {
      "name": "Mansur",
      "surname": "Bakirov",
      "patronym": "Maksutovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "1",
      "phone": "85657652311",
      "card_number": "1234 6543 1111 5535",
      "anydata": " something ",
      "anydata2": "hello"
    },
    "5": {
      "name": "Xamid",
      "surname": "Saliev",
      "patronym": "Aripovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "4",
      "phone": "85672115535",
      "card_number": "1234 2353 5444 2345",
      "anydata": " something ",
      "anydata2": "hello"
    },
    "6": {
      "name": "Bobur",
      "surname": "Qobilov",
      "patronym": "Axmetovich",
      "date_pub": "12.02.2019",
      "date_get": "12.03.2019",
      "status": "3",
      "phone": "85672612664",
      "card_number": "1287 3853 4734 5475",
      "anydata": " something ",
      "anydata2": "hello"
    }
  };
   return res;
}

function SearchPhone() {
   var phone = $('#phonesearch').val();

  var allPhoneNumbers = getAllPhoneNumbers();
  var sttr = '<tr class="" style="cursor: pointer;" data-toggle="modal" data-target="#myModal1"><th  scope="row" id="listnum_fp">';
  endtr = '</tr>';
  stth = '<th style="white-space: nowrap">';
  endth = '</th>';
  sttd = '<td style="white-space: nowrap">';
  endtd = '</td>';
  document.getElementById('cardmod_fp').innerHTML = "";
  
  for (const key in filter(phone, allPhoneNumbers)) {

    var f_i_sh = stth + res[key].surname + ' ' + res[key].name + ' ' + res[key].patronym + '' + endth;
    publicated = sttd + res[key].date_pub + endtd;
    willget = sttd + res[key].date_get + endtd;
    status = sttd + res[key].status + endtd;
    phone = sttd + res[key].phone + endtd;
    datarowout = sttr + (key - 1) + f_i_sh + publicated + willget + status + phone + endtr;
    document.getElementById('cardmod_fp').innerHTML += datarowout;

  }
}
</script>
<div class="table-responsive">
  <table class="table table-lg table-bordered shadow bg-light ">
    <thead>
      <tr>
        <div class="card-header text-right">
          <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-3"></div>
            <div class="col-md-3"></div>
            <div class="col-md-3">
              Phone input: <input id="phonesearch" onkeyup="SearchPhone(this.value)" type="text" class="form-control">
            </div>
          </div>

        </div>

        <tr>
          <th style="width: 40px;" scope="col">№</th>
          <th scope="col">Name</th>
          <th scope="col">Post Date</th>
          <th scope="col">Get Date</th>
          <th scope="col">Status</th>
          <th scope="col">Phone number</th>
        </tr>
    </thead>

    <tbody id="cardmod_fp">

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

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

Merging two arrays to create a JSON object

column_names: [ "School Year Ending", "Total Students", "American Indian/Alaskan Native: Total", "American Indian/Alaskan Native: Male", "American Indian/Alaskan Native: Female", "Asian/Pacific Islander: Total", "Asian/Pacific I ...

When values are deleted from an array object, the entire structure is altered even when browsing through the keys

Manipulating arrays within objects: -----code ------- var obj1 = { 'a': ['a','b','c','d'], 'b':['b','d','r','a']} Object.keys(obj1).forEach(element =& ...

Loading icon disappearing upon page refresh using window.location.reload()

After loading a javascript function on my page, I wanted to add a loading icon to show the user that something was happening. The loading icon worked initially, but disappeared as soon as the page finished loading and did not reappear during subsequent rel ...

Developing a comprehensive Java web service project with AngularJS, test-driven development/behavior-driven development, using Maven and Eclipse

Encountering some challenges while setting up a project to implement the full Java, Angular.js, TDD/BDD stack. While these challenges are not causing any major obstacles as of now, they have the potential to become one. Using Eclipse 4.6.0 Neon with WTP, ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

Retrieving the dimensions of a concealed element

I am facing a minor issue and I need some assistance in figuring out what I might be missing here. Here is my html code: <div class="drop-down-menu"> <div class="innerdrop-down-menu"> <div id="first-tab-cont"> <ul id=" ...

What could be causing the return of undefined upon execution?

function updateTitle(title) { title = "updated title"; } var currentTitle = "original title"; currentTitle = updateTitle(currentTitle); console.log(currentTitle) I'm just starting to learn JavaScript and I'm curious about why this code behav ...

How can I filter out strings and only keep the numbers in an array using JavaScript?

After searching through numerous similar questions, I have been unable to find a solution to this particular challenge. I am in need of a function that can remove all non-number items from an array while also modifying the existing array rather than creati ...

Performing logical operations on data following a POST request

I am currently developing an educational application for exams. In this app, a teacher creates exams and students answer them. Once the student has submitted all their answers, I want to display the exam results which will include the correct answers along ...

The best way to efficiently search a JavaScript object or an array of objects is by utilizing the most

In my JavaScript code, I am working with an array of objects like this: var arrayObjs = [ { id:abc123, radius:5.0}, { id:def235, radius:2.5},...] I have been using a for loop to search for a specific object with the id 'def235'. I'm curiou ...

Troubleshooting Limitation Problem with Bootstrap Multiselect

I recently created a multiselect dropdown menu using Bootstrap Multiselect. I successfully set a limit on the number of options that can be selected (in this case, 5), and once the limit is reached, the additional options become disabled. Everything works ...

Error encountered while displaying page following delete operation

exports.removeItem = function (req, res) { var idToDelete = req.params.id; var itemsInCart = req.session.items; var indexToRemove; _.each(itemsInCart,function (item) { if(item.id === idToDelete) { indexToRemo ...

The sorting functionality in Angular.js using the orderBy directive seems to be malfunctioning as it is not

Within this code snippet, @Model.jsonString represents a string. @model WebApplication1.Models.Car @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <html> ... <body ng-app="myModule"> <div ng-controller="myC ...

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Is there a way to manage a JSON file independently of my GitHub repository, like hosting and editing it separately?

I'm currently developing a Discord bot and am exploring options to host it using Heroku and GitHub. My plan is to store user data in a JSON file, but I'm facing challenges when trying to edit the file directly in the repository. I'm seeking ...

Preserve the original position of the inner <div> when animating the container <div> using JQuery

I am currently working on a small website and encountering some challenges with jQuery animation. My issue involves placing a single character text inside a circle and wanting it to grow when the user hovers over it, while keeping the inner text in its ori ...

Are there any jQuery plugins available that can automatically resize images to fit within a div in a collage-style layout?

I'm interested in creating a layout similar to what I see on for my portfolio project. My goal is to showcase images that span the full width, occupy 1/4 or 1/2 of the div, and fade in smoothly. I envision them arranging themselves in a dynamic news ...

Next.js is skipping server-side function calls

Issue arises when multiple server actions are invoked, some taking longer due to large dataset retrieval. https://i.sstatic.net/RCxcK.png During reloading, drag and drop functionality for widgets is delayed until all server actions are completed and loadi ...

Executing a JavaScript function during page load in an ASP.NET application

Similar Question: Javascript code to run after page has loaded In my ASP.NET 4.0 application, I am using JavaScript to show the client's time zone offset in a text box:- ` <script type="text/javascript"> function GetTimeZoneOffset() { ...

Protractor is able to achieve successful test results without actually executing the tests

SYMPTOMS When running Protractor, the tests pass successfully, but the pages do not load. Instead, they appear blank with "data:text/html" in the address bar (refer to the screenshot). Although the tests show as passed, there are 0 assertions being made. ...