Not quite sure about the best way to showcase the results // using JavaScript

My code is posted below. I am trying to achieve a functionality where, upon clicking the 'Calculate Price' button, the results showing the number of cars, type of cars, and their respective prices are displayed beneath the button. Despite this being seemingly easy to implement, I have been facing difficulty in getting it to work.

Here is the HTML code snippet:

<!DOCTYPE html>
<html>
<body>
    <form name="Cars">
        <h1>Car Sales</h1>
        <p>Which type of car would you like (A, B or C)</p>
        <input type="text" name="CarType"><br>
        <p>How many cars would you like (1-100)</p>
        <input type="text" name="CarNumber"><br>
        <br>
        <button onclick="return beginfunction()">Calculate Price</button>
        <p id="message"></p>
        <script src="car.js">   </script>
    </form>
</body>

JavaScript function:

function beginfunction() {
  var CarType = document.forms["Cars"]["CarType"].value;
  var CarNumber = document.forms["Cars"]["CarNumber"].value;
  var CarPrice;
  if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
    CarTypeError = "Invalid Car Type";
    document.getElementById("message").innerHTML = CarTypeError;
    return false;

  }


  {
      if (isNaN(CarNumber)) {
        CarNumberError = "Invalid Quantity Entered";
        document.getElementById('message').innerHTML = CarNumberError;
          return false;
      }

  }
{
  if (CarNumber >0 && CarNumber <10)
  {

  }
  else
  CarError = "Invalid";
  document.getElementById('message').innerHTML = CarError;
  return false;
}
{
if (CarType == 'A') {
    CarPrice = 30;
} else if (CarType == 'B') {
    CarPrice = 20;
}  else if (CarType == 'C'){
  CarPrice = 10;
}
}

}

Answer №1

While working on the CarPrice calculation, remember to actually utilize the variable you have defined. You could assign it within the same <p> tag where error messages are being set. Here's an example code snippet:

if (CarType == 'A') {
    CarPrice = 30;
} else if (CarType == 'B') {
    CarPrice = 20;
}  else if (CarType == 'C'){
  CarPrice = 10;
}
document.getElementById('message').innerHTML = CarPrice;

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 create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

Avoid receiving input for a button that is being covered by another button

I am currently developing an Idle Game and I am looking to include 'buy buttons' for purchasing buildings, along with a sell button embedded within the buy button. Just as a heads up, these buttons are represented by DIVs acting as buttons. Here ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

Obtaining specific data from the forEach iteration, post-click event with JavaScript

Trying to access the value from a Tree-structured Array of Objects stored in Local Storage, Created a function that retrieves values from local storage using forEach and displays them on the screen. Clicking on the Yes/No button triggers the same functio ...

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

Charting data from MongoDB with Highcharts column chart

Having trouble creating a column chart with Highcharts in Node.js, fetching data from MongoDB. Specifically stuck on the series option - any help is appreciated. Here's an excerpt of my code in the EJS file: <html> <head> <meta ht ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

Utilize regular expressions in TamperMonkey to extract specific groups of text

I'm currently working on a TamperMonkey userscript that aims to identify URLs matching a specific pattern, visit these pages, extract relevant information, and then update the link for each URL with the extracted text. I'm facing some challenges ...

Navigate to items within a content block with a set height

I have a <div> that has a fixed height and overflow-y: scroll. Inside this div, there is mostly a <p> tag containing a long text with some highlighting (spans with background-color and a numbered id attribute). Just to note, this is an HTML5 a ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

Mistakes in my async/await workflow: How am I incorrectly loading and injecting this external script?

Encountering a simple problem: some calls to refresh() cause window.grecaptcha to become undefined. It doesn't happen all the time, probably due to network delays. Debugging this issue is proving to be tricky, especially since I'm still new to th ...

Angular Custom Pipe - Grouping by Substrings of Strings

In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe impleme ...

Setting the select option in AngularJS with predefined options can be easily achieved with

I am encountering an issue with a select element that has predefined options. Even though the select element is using ng-model, when the model is set to one of the option values, it fails to be selected. Below is the snippet of HTML code: <select clas ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...

What is the best way to implement a fadeout or timeout for success and warning alerts in OpenCart 2.2?

Is there a way to set a timeout for alert boxes in Opencart 2.2 so that they disappear after a few seconds? I've tried the code below, but it didn't work out. Alternatively, is it possible to make the popup disappear when clicking anywhere on the ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...