Organizing search findings in a JavaScript table

What I'm currently doing is using document.write in my application to display search results to the user. However, I want these results to be shown in a table within <div class="main">. The catch is that I don't want the table visible at the outset - only when displaying results. How can I achieve this? Appreciate your assistance! :)

https://jsfiddle.net/48prjb62/

HTML:

<!DOCTYPE html>
<html lang="en-GB">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
    <link href="css/style.css" rel="stylesheet" type="text/css">
    </script>
    <link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
...

<p>CSS:</p>

<pre><code>html{
 margin: 0;
 padding: 0;
}
body{
    margin: 0;
    padding: 0;
}
.margin{
...

JS:

function phoneContract(brand, model, network, minutes, texts, data, upcost, monthlycost, length) {
    ...
}

var contract=[];
...

function checkBrand(){
    ...
}

function checkNetwork(){
    ...
}

var button = document.getElementById("search");
button.addEventListener("click", search, false);
var minutes
function slidefunction() {
...

Answer №1

To hide the table by default, apply display:none, and then change it to display:block when a result is found. Inline, set display:none on the element and dynamically switch it using JavaScript within the conditional statement if(matches > 0).

Answer №2

Ensure to declare a variable named "searchResult" right before initiating your "for" loop within the "search()" function. This variable will store each result line which you will concatenate. Finally, display the result in the "main" div:

function search() {
    var brandCheck = checkBrand();
    var networkCheck = checkNetwork();
    var model = document.getElementById("phone_model"); 
    var f = document.getElementById("internet");
    var g = document.getElementById("upcost");
    var h = document.getElementById("month_cost"); 
    var i = document.getElementById("contract_length"); 

    // Initialize searchResult variable
    var searchResult = "";
    
    for (var p = 0; p < contract.length; p++) {
        var matches = 0;
        var total_number_of_conditions = 10;

        if (brandCheck == contract[p].brand) matches += 1;
        if (model.value == contract[p].model) matches += 1;
        if (networkCheck == contract[p].network) matches += 1;
        if (minutes >= contract[p].minutes) matches += 1;
        if (text >= contract[p].texts) matches += 1;
        if (f.value == contract[p].data) matches += 1;
        if (g.value == contract[p].upcost) matches += 1;
        if (h.value == contract[p].monthlycost) matches += 1;
        if (i.value == contract[p].length) matches += 1;

        if (matches > 0) {
            var percentage_matched = 100 * (matches / total_number_of_conditions);
            
            // Concatenate lines of the table result
            searchResult += "<tr><td>" + contract[p].brand + 
                            "</td><td>" + contract[p].model + 
                            "</td><td>" + contract[p].network + 
                            "</td><td>" + contract[p].minutes + 
                            "</td><td>" + contract[p].texts + 
                            "</td><td>" + contract[p].data + 
                            "</td><td>" + contract[p].upcost + 
                            "</td><td>" + contract[p].monthlycost + 
                            "</td><td>" + contract[p].length + 
                            "</td><td>" + percentage_matched + "%</td></tr>";   
        }
    }

    // Check if there is any result
    if(searchResult != ""){
        searchResult = "<table>" + searchResult + "</table>";
    }

    // Display the result in the main div
    document.getElementsByClassName('main')[0].innerHTML = searchResult;
}

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

What is the best way to verify the authenticity of a entered captcha code in php?

I'm struggling with validating a captcha code in my registration form. I need to check if the entered captcha code is correct before allowing the user to complete the registration process. If the code is invalid, I want to display an error message. I ...

How can a child component's height be dynamically adjusted according to its parent's size?

Here is a link to the codesandbox I created: https://codesandbox.io/s/jolly-agnesi-j5bzr?file=/src/App.js Below is a screenshot of the project: https://i.sstatic.net/GdYVZ.png The red background content is dynamically generated, causing the height of th ...

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

Implementing siteSpeedSampleRate in Google Analytics with AngularJS - a step-by-step guide

I utilized the following link https://github.com/revolunet/angular-google-analytics to incorporate Google Analytics into my AngularJS 1.5 project. However, I'm having trouble setting the siteSpeedSampleRate. I injected the AnalyticsProvider and attemp ...

Establishing session management for tasks in Node.js

I'm currently developing a web application using Node JS and encountering an issue with the session store in req. For my sessions to work, I have set up my app.js like this: // Enable sessions app.use(session({ secret: '***********', ...

Is there a way to dynamically assign ng-include or ng-controller in Angular JS?

I'm a beginner with Angular JS and after some research, it seems like what I want to achieve might not be possible. However, I'd like to explore if there is an alternative solution that can provide a similar outcome. My goal is to populate a pag ...

Developing a unique note-taking solution by leveraging JQuery mobile and phone gap technology

I am currently working on an app using JQ Mobile and PhoneGap. One feature that I would like to implement is a 'Notes Taking' page with the following functionalities: Create new notes and save them locally Retrieve notes whenever needed Edit an ...

Applying styles to an active router-link in Vuejs: A step-by-step guide

I have a sidebar that contains multiple sidebar items like the following: <side-bar> <template slot="links"> <sidebar-item :link="{name: 'Home', icon: 'ni ni-shop text-primary', path: '/dashboard'} ...

Creating interactive ng-models for form controls using AngularJS

I am working on a project where I have an Array in my controller. This Array is being used to dynamically generate input fields on the page. Here is a snippet of my AngularJs code: var app = angular.module('plunker', []); app.controller(' ...

Refreshing a Nested Component Within a Parent Component in React

Currently, I am in the final stage of a small project where a Higher Order Component (HOC) is being utilized to display a basic Tinder-like application. The internal component is a class-based component containing its own fetch() call that presents user d ...

Can the CSS property "float: none;" interfere with the Javascript function "ng-click"?

This particular issue is quite strange. Setting "float: none;" appears to be preventing the execution of Javascript (ng-click). new.html.haml (where "float: none;" is located) .container{ng: {controller: 'sample_1_controller'}} %nav.bread.m ...

Integrating jQuery into the functions.php file of a Wordpress

I have been using a jQuery script in Unbounce and now I want to implement it on my Wordpress page. I believe I will have to insert this into the child theme functions file, but I know it requires some PHP code as well. As I am still fairly new to this proc ...

What is the best way to bring a list from one .js file into my main.js file?

Here is a demonstration using Ania Kubow's Climate change API. My query is: I have a lengthy list similar to this one, and I would like to store it in a separate file named "exampleList.js" and then import it into my main.js file. const newspapers = ...

Creating an object using a string in node.js

I have a string that I am sending from AngularJS to NodeJS in the following format. "{↵obj:{↵one:string,↵two:integer↵}↵}" //request object from browser console To convert this string into an object and access its properties, I am using the serv ...

Encountering: Unable to break down the property 'DynamicServerError' of 'serverHooks' as it does not have a defined value

An error has arisen in a Nextjs app with TypeScript, specifically in the line of my react component which can be found here. This is my inaugural package creation and after several trials, I managed to test it successfully in a similar vite and TypeScript ...

Split a JavaScript string at a mathematical operator while ensuring that the operator is still included in

Hello there, I am attempting to break down a string of text into an array whenever a '+' or '-' is present. First of all, I am looking for a way to split at the plus sign and ensure it is included in the array. I have experimented with ...

Unique ways to serialize an HTML element efficiently: JavaScript tricks

Is there a way to store a reference of an HTML tag for future use? For instance, if I click on a div and save a pointer to that div in JavaScript, is it possible to serialize this pointer and then de-serialize it to use in another part of the web applicat ...

Which is the better choice: utilizing object literals or constructor functions?

I'm feeling a bit puzzled about the best way to create an object in JavaScript. It appears that there are at least two methods: one involves using object literal notation, while the other utilizes constructor functions. Is there a specific advantage o ...

Tips for effectively utilizing node modules that have yet to be installed without encountering any errors

I am looking to create a setup script for my NodeJS application. The script will: Establish system roles for users Create a root category for posts Finally, create a system admin user for the initial login These details will be saved in a database. Ad ...

Swap out the CSS line for a PHP conditional statement

My goal is to change a CSS line when a specific condition is met. When I click on the Ok button, a lot of data is displayed. Depending on the selection made in a combo-box, I want the text to appear either in red or black. I tried using JavaScript for this ...