JavaScript Form for computing Daily Rate from JSON

I am looking to retrieve pricing information from a JSON file based on the Room, Season, and number of nights specified.

Currently, the HTML code triggers an alert each time one of the three form inputs is selected.

<!DOCTYPE html>
<html>
<body>

<script src="showprice.js"></script>
<h3>Daily Rate Calculator</h3>

<form>
<label for="aroom">Choose Room:</label>
<div id="room"></div><br>
<label for="aseason">Choose Season:</label>
<div id="season"></div>



<br>
  <label for="days">Number of days:</label>
  <select name="days" id="days" onchange=loadNumber(this.value)>
    <option value="-">-</option>
    <option value="0">1</option>
    <option value="1">2</option>
    <option value="2">3</option>
    <option value="3">4</option>    
    <option value="4">5</option>
    <option value="5">6</option>
    <option value="6">7+</option>
  </select>
</form>

<br>
<div id="demo"></div>
</body>
</html>

Here's the current implementation of showprice.js:

var troom
var tseason
var tday

 async function start(){


        const response=await fetch("pricing.json")
        const data=await response.json()
        createRList(data.rooms)
       console.log (data.rooms)
        createSList(data.rooms.Spanish)
        //console.log (data.message.rooms.keys)
        createRate(data.message.troom.tseason[tday])
        console.log (data.message.troom.Entries(tseason)[tday])
      }
      start()

function createRList(rListic){
      document.getElementById("room").innerHTML=`
                    ${Object.keys(rListic).map(function(roomic){
                          return `<input onMouseUp="loadByRoom(this.value)" type="radio" id="${roomic}"
                          name="aroom" value="${roomic}">
                          <label for="${roomic}">${roomic}</label><br>`
                  }).join('')
                
}`
}

function createSList(sList){
  document.getElementById("season").innerHTML=`
                ${Object.keys(sList).map(function(seasonic){
                      return `<input  onClick="loadBySeason(this.value)" type="radio" id="${seasonic}"
                      name="aseason" value="${seasonic}">
                      <label for="${seasonic}">${seasonic}</label><br>`
              }).join('')
            
}`
}




function loadByRoom(roomic) {
 alert (roomic)
 troom=roomic
}
function loadBySeason(seasonic) {
  alert (seasonic)
 tseason=seasonic
 }
 function loadNumber(days) {
  alert (days)
  tday=days
 }

 function createRate(drate) {
  document.getElementById("demo").innerHTML=`Daily Rate: £${drate}`
 }

This is the content of pricing.json:


       { "rooms": {
              "Greek": {  "Peak":[200,190,180,170,160,150,140] ,"Mid":[190,180,170,160,150,140,130],"Off":[180,170,160,150,140,130,120]},
              "Spanish": {  "Peak":[220,210,200,190,180,170,160] ,"Mid":[205,195,185,175,165,155,145],"Off":[200,190,180,170,160,150,140]},
              "Italian": {  "Peak":[210,200,190,180,170,160,150] ,"Mid":[200,190,180,170,160,150,140],"Off":[190,180,170,160,150,140,130]}
                }
        }

I have managed to output all the data in the console, but I am struggling with how to determine and display the specific rate needed to pass as an argument to the createRate function.

Answer №1

drate is not a commonly used identifier in HTML or dynamically generated by JavaScript (DOM). I would recommend first mapping this identifier to the corresponding element either in the HTML code or through DOM manipulation.

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

Inquiring about how to make a Javascript HTTP POST request?

Imagine having a website with a snippet of javascript that, when triggered by a visitor clicking a button, sends an HTTP request to an external URL. Now, if the external URL which receives this request attempts to trace the IP address or host of the sourc ...

What exactly does the Javascript object syntax signify? (specifically in a Vue script)

Can anyone explain the purpose of this statement and the difference between using const and var? const { SearchIcon } = myApp.icons; I am currently exploring Vue and still relatively new to Javascript. This code snippet appeared in a tutorial example. The ...

Incorporate TypeScript with Angular 2 to construct a dictionary with <key, value> pairs. Then, utilize a JSON file to populate the dictionary with data

I am in need of assistance with creating a dictionary or list with a specific structure. I have prepared a json file within my angular 2 project, and I would like to load this data into the dictionary that I am creating. Sample content from my Json file: ...

Webpack does not automatically detect and compile changes made to SCSS files

Currently, I am attempting to consolidate the CSS and JS into one main.js file, but I am encountering an issue where the changes are not being reflected. Despite no visible errors, the terminal fails to display any issues and works smoothly for React. The ...

Is it better to use project remote images instead of local ones?

I am currently experimenting with implementing the MosaicUI project from here into my own project. One issue I am encountering is figuring out how to transition from loading local images stored in a json file to fetching images from my web server. Has any ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...

Display JSON information in a grid using JQuery

I'm on the lookout for a simple json grid plugin to make my life easier. I need to populate a grid using JSON/Ajax, but the catch is that the amount of data or columns will vary each time, so it needs to be able to adapt accordingly. For example, a p ...

Errors that occur during Javascript runtime in the Express framework

I'm currently working on an Express app with several routes. One of them looks like this: router.post('/upload', (req, res) => { let audioFile = req.files.audioFile; const file = __dirname + '/../' + req.body.uploadLocation ...

Is it possible to utilize a route path in a JavaScript AJAX request?

So I have a situation with an ajax call that is currently functioning in a .js file, utilizing: ... update: function(){ $.ajax({ url: '/groups/order_links', ... However, my preference would be to use the route path instead. To achieve ...

A different approach to calling JavaScript functions

I have a method that populates an array. I would like to utilize it in this manner: arrayname.fill("First Array"); And not like this: arrayname = fill("First Array"); What approach should I take? function fillArray(name) { let newArray = ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

Where the package.json file resides

Is there a designated location for the package.json file in a project, like within the project directory? Where should the package.json file be located in a multi-component project? What is the significance of having version 0.0.0 in th ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

reactjs error: Attempting to utilize the toLowerCase method on an undefined property during double mapping

My issue involves a JSON structure that requires mapping a function twice in a loop to access objects within an array. Once mapped, I need a textbox for searching the data list. However, I am encountering the following error: TypeError: Cannot read proper ...

Is it safe to use $http.get() in AngularJS to request a JSON configuration file securely?

Using a relative path, I am retrieving a JSON file that contains sensitive authentication data with the following code: $http.get('app/config.json').then(function (data) {} Although it's currently functioning correctly, I have concerns abou ...

Combine and transform multiple hierarchical JSONs into a new format

I'm facing a challenge where I need to merge two JSON objects and convert them into a different format using TypeScript in a React project. Initially, I tried implementing this with a recursive function as well as a reducer, but unfortunately, it didn ...

Using three.js to create a rotating analog clock in Javascript

I currently have a traditional clock displayed in my setting that I want to synchronize with the current time. I am able to keep the clock running by calculating each hand's rotation every second, but I am encountering peculiar issues with the minute ...

Finding and removing the replicated keys within a JSON array while also retrieving the corresponding JSON path

I have a JSON object that looks like this: {"response":{"result":{"Leads":{"row":[{"LEADID":"849730000000063017","SMOWNERID":"849730000000061001"},{"LEADID":"849730000000063015","SMOWNERID":"849730000000061001","HIII":"hello"},{"LEADID":"84973000000006 ...

What determines why the input value is restricted to being of type string?

In my ReactJS component, I am struggling to set the state value as an integer using setState. This is causing issues with the radio button not being checked. constructor(props) { super(props); this.state = { frequency: 1, } handleSelectChange(eve ...

Converting DataSet to JSON using ServiceStack.Text

I'm facing an issue with serializing a dataset to JSON using ServiceStack.Text (from Nuget.org). I'm currently working with the version 4.0.50 and VS 2015. The error message that keeps popping up is: Process is terminated due to StackOverflowE ...