What is the method for inserting JSON data into a select element's options?

Below is the HTML code snippet provided:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="CarInfoStyle.css">
</head>
<script src="CarInfoJavascript.js"></script>

<body>
    <div class="searchfilter">
        <div class="searchwrapper">
            <select class="selectClass" id="minYear">
                <option value="minYear">Select Year</option>
                <option value="(All)">ALL</option>
                <option value="2015">2015</option>
                <option value="2014">2014</option>
                <option value="2013">2013</option>
                <option value="2012">2012</option>
                <option value="2011">2011</option>
                <option value="2010">2010</option>
                ...
            </select>
            to
            <select class="selectClass" id="maxYear">
                <option value="maxYear">Select Year</option>
                <option value="(All)">ALL</option>
                <option value="2015">2015</option>
                <option value="2014">2014</option>
                <option value="2013">2013</option>
                ...
            </select>


            <select id="make" onchange="DropdownOption()">
                <option value="" selected disabled>Make</option>
                <option value="alfa romeo">ALFA ROMEO</option>
                <option value="audi">AUDI</option>
                ...
            </select>;

            <select id="Model" disabled>
                <option value="model" name="model" selected disabled>Model</option>
            </select>;

            <input type="text" size="20" name="searchbox">
            <input type="button" name="searchbutton" value="Search" onclick="createTable()">
        </div>

    </div>

    <div class="CSSTableGenerator">
        <table id="MyTable" cellspacing='0'>
            <tbody>
            </tbody>
        </table>
    </div>

</body>

</html>    

The following JSON object data snippet was also given:

var carData = [{
    "ConditionNotes": {},
    "Photos": {},
    ...

// Truncated for brevity
}]; 

And here is the JS Code provided:

function createTable() {

    var table = document.getElementById("MyTable");
    table.innerHTML = "";
    var header = table.createTHead();
    var row = header.insertRow(0);
    //...Cells initialization

    var makevalue = document.getElementById("make").value;
    var modelvalue = document.getElementById("Model").value;
    var minYearvalue = parseInt(document.getElementById("minYear").value);
    var maxYearvalue = parseInt(document.getElementById("maxYear").value);

    for (var i = 0; i < 757; i++) {
        // Condition block whose purpose isn't well-defined. Adjusting it.
        if (carData[i].Make === makevalue && carData[i].Model === modelvalue) {
          var rowCount = table.rows.length;
          var row = table.insertRow(rowCount);
          var chassisCell = row.insertCell(0);
          var yearCell = row.insertCell(1);
          var makeCell = row.insertCell(2);
          var modelCell = row.insertCell(3);
          var modelGradeCell = row.insertCell(4);
          var shipNameCell = row.insertCell(5);

          chassisCell.innerHTML = carData[i].RealChassisNo;
          yearCell.innerHTML = carData[i].Year;
          makeCell.innerHTML = carData[i].Make;
          modelCell.innerHTML = carData[i].Model;
          modelGradeCell.innerHTML = carData[i].Grade;
          shipNameCell.innerHTML = carData[i].ShipName;
        }
    }
}

function DropdownOption(carData) {
    document.getElementById("Model").disabled = false;
    var model = document.getElementById("Model");
    var option = document.createElement("option");
    var make = document.getElementById("make").value;
    model.innerHTML = "";

    // Option creation based on 'make' selection

    // Example for 'audi', adjust others similarly
}

If you need further assistance, provide more context regarding the condition logic requirement.

Answer №1

There is an issue with the array storing the lowercase values of the car make. To resolve this, update your code as follows:

if (carData[i]['Make'].toLowerCase() == makevalue.toLowerCase() && carData[i].Model == modelvalue && (carData[i].Year >= minYearvalue && carData[i].Year <= maxYearvalue)) {

A typo has been identified in your code:

var chassisCell = row.insertCell(o);

The correct code should be:

var chassisCell = row.insertCell(0);

For a functional demonstration, refer to the following example: http://jsfiddle.net/klickagent/dyrLw3jf/2/

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 Foundation 6 Zurb Template is not compatible for offline use

After successfully installing Foundation 6 Zurb Template via the cli, I encountered no issues. I then added the missing babel install and everything worked fine online. However, BrowserSync does not seem to work offline. Upon initiating watch, I receive a ...

Showing C# File Content in JavaScript - A Step-by-Step Guide

Is there a way to showcase this File (c#) on a JavaScript site? return File(streams.First(), "application/octet-stream", Path.GetFileName(element.Path)); I am looking for something similar to this: <img id="myImg" src="_____&qu ...

``There seems to be a problem with decoding JSON data in Swift, as some information

I am currently working on querying the NASA image API with Swift 4. After testing my network request and decoding setup using JSONPlaceholder, everything was functioning properly. However, when I switched to the NASA API URL and JSON data structure, I enco ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

What sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...

What are some strategies for keeping the focus state on the parent item in a dropdown menu?

When I interact with the dropdown menu in my navigation bar, the color changes for the child items. How can I make sure that the parent item maintains the same colored background even after clicking elsewhere on the page? To better understand the issue, i ...

Exploring the power of async/await in conjunction with loops

My JavaScript code is designed to extract content from HTML pages and perform a crawling operation. However, the issue arises with asynchronous execution due to a request function. I attempted to utilize Promises and async & await to address this probl ...

Error message: "Angular.js encountered a typeError stating that V2.example is not a function"

Having recently started learning Angular.js, I came across a tutorial that was created about a year ago. In this tutorial, I am attempting to implement a search feature that takes user input and searches for it on Github.com. Below is the HTML code snippet ...

When AJAX is invoked, the HTML content fails to display within a div

The following is the ajax script I am currently utilizing: mypage.php $(".sales_anchor").click(function(e) { e.preventDefault(); var store_username = $("#storeUsername").val(); var store_id = $("#storeID").val(); var sale_id = $(this).a ...

Convert JSON Array to List via Deserialization

I attempted the suggested solution, but I am still encountering issues when trying to print the list. Below is the JSON data: var result = [ { "id": 1409636 }, { "id": 1499272 }, { "id": 1409587 }, { ...

Combining the devexpress dxDataGrid with Angular's $scope for seamless web development

I'm encountering difficulties with binding $scope in angular and dxDataGrid. Utilizing the devexpress library dx.all.js, which enhances the dxDataGrid with various features, I have a div for dx-data-grid and attempting to transfer the selected row da ...

The powerful combination of Ajax and Django creates a dynamic Like button

Encountering difficulties while trying to implement a basic like button feature. Despite following various tutorials, clicking on the Like button does not yield any action. See below: models.py class Comentario (models.Model): titulo = models.CharFie ...

Transferring a single dataset from a table to a pop-up modal using Angular

I am working on a table to display entries for a contest, extracted from a database using PHP and converted into a .json object for AngularJS and JavaScript. I want to add a modal feature so that when a "judge" clicks on an entry, they can view its details ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

A guide on how to parse bash variables into a JSON format

I need help with adding tags to my ec2 instances by passing the key and value via bash variables. #!/bin/bash image="" instancetype=t2.small key1=type value1=test key2=description value2=test123 aws ec2 run-instances --image-id ${image} --count 1 --in ...

How can I effectively display personalized information from an MSAccess database on a WordPress website?

I am seeking advice from experienced Wordpress developers. My organization possesses an internal MS Access database that comprises various tables, reports, and input forms. The structure of the database is relatively straightforward, encompassing informati ...

The page loads successfully at first, but upon refreshing, a 404 error occurs when using Zeit, Nextjs, and now

After recently updating from now v1 to v2, I encountered an issue where my pages would return a 404 error when reloading after pushing to production using now --prod. While everything worked fine locally with now dev, the routing seemed to be causing confu ...

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...

Exploring the world of JSON communication through MVC Web API: A comprehensive guide

Similar cases to mine have been answered before, but my specific needs always seem to differ from others' problems. I am facing an issue where I'm sending JSON data from my HTML page to the MVC Web API, but unfortunately, the data I receive is a ...

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...