Receiving user input from a form element to incorporate into a JavaScript function for rendering on the webpage

Currently, I am attempting to gather input from the user in the form of two numbers. Upon clicking a button that executes a JavaScript function, the goal is to display the result on the webpage. However, upon running the code, it returns

NaN

I'm struggling to figure out how to resolve this issue. Is there a way for me to incorporate a tip display on the webpage?

This is my HTML:

<!DOCTYPE html>
<html>
    <head> 
        <title> Custom Tip Calculator by Jonah </title>
        <div id = "links">
        <script src = "functions.js"></script>
        <link type = "text/css" rel = stylesheet href = "design.css">
        <link href="https://fonts.googleapis.com/css?family=Bitter" rel="stylesheet">

        </div>
    </head>
    <body>
        <div id = "cool_main">
        <h1 id = "title"> Custom Tip Calculator </h1>
        <h2 id = "developer"> Created by Jonah Johnson </h2>
        </div>
        <p id = "main_para"><b> Enter the cost of the meal and the tax percentage, then click OK!</b></p>

        <form id = "meal_cost">
        Input Total Meal Cost:<br>
        <input type="text" id = "meal__cost" name="mealcost" /><br>
        </form>
        <form id = "tax_percent">
        Input Tax Rate (in percent):<br>
        <input type ="text" id = "tax_per" name="taxpercent" ><br>
        </form>
        <h4 id = "per"> % </h4>
        <button id = "getTip" onclick = "calculateTip()"> OK </button>
    </body> 
</html>

This is my JavaScript:

var taxValue = document.getElementById("tax_per").value;

var mealCost = document.getElementById("meal__cost").value;

function calculateTip() {
    document.write(taxValue * mealCost);
}

This is my CSS:

div {
position: relative;
left: -490px;
}



#title {
font-family: "Bitter", sans-serif;
border: 0px solid black;
width: 225px;
padding: 10px 24px;
background-color: #dbdbcb;
border-radius: 4px;
box-shadow: 10px 10px 5px  #888888;
position: relative;
left: 531px;
font-size: 40px;
text-align: center;

}

#developer {
font-family: "Bitter", sans-serif;
border: 0px solid black;
width: 300px;
padding : 5px 10px;
text-align: center;
background-color: #dbdbcb;
border-radius: 10px 10px;
box-shadow: 10px 10px 5px #888888;
position: relative;
left: 510px;
}

#main_para {
border: 1px solid black;
width: 415px;
position: relative;
left: 0px;
font-family: "Bitter", sans-serif;
padding: 4px 10px;
background-color: #dbdbcb;
border-radius: 10px 10px;
}

#meal_cost {
    border: 0px solid black;
    width: 400px;
    height: 100px;
    padding: 10px 10px;
    text-align: center;
    font-family: "Bitter", sans-serif;
    background-color: #dbdbcb;
    box-shadow: 10px 10px 5px #888888;
    position: relative;
    left: 550px;
    bottom: 200px;  
    font-size: 40px;

}

#tax_percent {
    border: 0px solid black;
    width: 400px;
    padding: 10px 10px;
    text-align: center;
    font-family: "Bitter", sans-serif;
    font-size: 40px;
    background-color: #dbdbcb;
    position: relative;
    box-shadow: 10px 10px 5px #888888;
    left: 550px;
    bottom: 170px;
}

#per {
    position: relative;
    left: 856px;
    bottom: 226px;
    width: 10px;
    font-family: "Bitter", sans-serif;

}

If you have any advice or guidance, it would be greatly appreciated. Additionally, having the ability to customize the displayed value using CSS would be beneficial.

Answer №1

function calculateTotal() {
var taxValue = parseInt(document.getElementById("tax_per").value);

var mealCost = parseInt(document.getElementById("meal__cost").value);

    document.write(taxValue * mealCost);
}
<div id = "cool_main">
        <h1 id = "title"> Meal Cost Calculator </h1>
        <h2 id = "developer"> Created by Joe Smith </h2>
        </div>
        <p id = "main_para"><b> Enter the total cost of the meal and the tax percentage, then click OK!</b></p>

        <form id = "meal_cost">
        Total Meal Cost :<br>
        <input type="text" id = "meal__cost" name="mealcost" /><br>
        </form>
        <form id = "tax_percent">
        Tax % :<br>
        <input type ="text" id = "tax_per" name="taxpercent" ><br>
        </form>
        <h4 id = "per"> % </h4>
        <button id = "getTip" onclick = "calculateTotal()"> OK </button>

Remember to convert string data into Integer or Float when performing calculations.

var taxValue = parseInt(document.getElementById("tax_per").value);

var mealCost = parseInt(document.getElementById("meal__cost").value);

You can also use parseFloat if necessary.

Answer №2

You made a mistake with the variable naming conventions and need to fetch the value when the user clicks the button:

<!DOCTYPE html>
<html>
    <head> 
        <title> Tip Calculator by Jonah </title>

    </head>
    <body>
        <div id = "cool_main">
        <h1 id = "title"> Tip Calculator </h1>
        <h2 id = "developer"> Developed by Jonah Johnson </h2>
        </div>
        <p id = "main_para"><b> Enter the meal cost then a tax percentage, and hit OK!</b></p>

        <form id = "meal_cost">
        Meal Total Here :<br>
        <input type="text" id = "meal__cost" name="mealcost" value="0" /><br>
        </form>
        <form id = "tax_percent">
        Tax Here (in percent) :<br>
        <input type ="text" id = "tax_per" name="taxpercent" value="0"><br>
        </form>
        <h4 id = "per"> % </h4>
        <button id = "getTip" onclick = "addTogether(); return false;"> OK </button>

        <div id = "links">

        </div>
        <script >

            function addTogether() {
                var taxValue = parseFloat(document.getElementById("tax_per").value);

                var meal__cost = parseFloat(document.getElementById("meal__cost").value);

                document.getElementById("links").innerHTML= taxValue * meal__cost;
                return false;
            }

        </script>


    </body> 
</html>

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

VueJS is known to cause divs to reach towering heights on buildings

After running npm run build on my VueJS project, the columns in my grid inexplicably stretch to an enormous height. I've spent about 3 hours trying to find the cause, tweaking settings and combing through my CSS files with no luck. It seems like this ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

Guide to positioning a button on top of another button using Vuetify

I'm facing an issue where I want to add a button on a clickable card, but clicking the button also triggers the card click event. Here's my current code snippet: <v-card @click="show = !show"> <v-img src="https://cdn.vuetifyjs.com/im ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

Struggling to receive information from a third-party API using a token in a React application

Currently, I am attempting to retrieve data from a third-party API. While it functions properly on Postman, I am striving to successfully make a request and access the data within my React project. The public API in question is: https://api.securityscorec ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Ensure consistency in the heights of div elements, even when the images contained within have varying heights

I created a bootstrap webpage with a row of DIVs, each containing an image. As I resize the browser window, I noticed that the height of the first two DIVs remains consistent, but the third div's height varies because the image is only 50 pixels high. ...

What could be the issue with my injection supplier?

When running the following code, the configuration works fine, but an error is returned: Uncaught Error: [$injector:unpr] Unknown provider: AngularyticsConsoleHandlerProvider <- AngularyticsConsoleHandler <- Angularytics Code snippet: angular.modu ...

The inability for two dynamically created Ajax elements to identify one another is hindering their interaction

Hello wonderful people at Stack Overflow, I've been attempting to create a table generator that dynamically creates two tables upon the click of a button. So far, it's been quite a frustrating journey full of roadblocks... Currently, my approac ...

Tips for using jQuery to slowly change a CSS property to "auto"

I've encountered a situation where I have an element styled with position:fixed, and bottom: auto;. When I apply the command .animate({bottom : '10%'});, it smoothly slides to the specified position. However, when I try to set it back to its ...

Filtering elements in a table using jQuery

Can anyone provide a solution to display students without a class and hide the rest (where td Class-name is empty) using only jQuery or JS? I tried looking in the documentation but got lost. Any help would be appreciated. Example: table image The table ...

reach an agreement on the implementation of infinite scrolling when navigating backwards

I'm looking to create a feature where clicking the back button will return me to the same position on the page. A great example of this is on . If you scroll down, click on a product, and then go back from the product page, you'll be taken back t ...

Preserve the newline character within a string in JavaScript

One of my API methods returns an RSA key in the following format: "publickey" : "-----BEGIN PUBLIC KEY-----\nMIGfMA0G CSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5WleAVeW5gySd QVFkTi44q1cE\ncWDT2gmcv2mHcWhwI/9YqGV2LqpMASe 4t4XS/88fvTTHafHn1KaL9F7d73T9k4cp&bs ...

Leverage JSON as the primary data source for Assemble.io

Can Assemble.io be used to compile json files into HTML using templates? If so, how can I configure my gruntfile to accomplish this? Overview of My Folder Structure: Data productlist1.json productlist2.json productlist3.json productdetail1.json product ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Display JSON information in a table within a dropdown menu

I have a JSON dataset where each key is represented as a column in a table. I am looking to populate each column with data from the JSON as select boxes. For example, I want to display all "country" values from the JSON as select options in the COUNTRY col ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

Tips for arranging my list within my list-group-items to create a visually appealing layout

I've encountered an issue where the alignment of list-group-items inside a card container is not correct. I am using Bootstrap 4 and my aim is to neatly align all 3 fields in a tabbed column layout. Any suggestions on how to achieve this are welcome. ...

Why is my popover not showing in AngularJS?

I've integrated this particular component into my project, but unfortunately, when I click on the icon, the popover does not appear. The expected behavior is that clicking on the icon should trigger the display of the popover, however, currently noth ...

Looping through mysql data horizontally within a div tag

Looking for assistance to create a content loop similar to the one on this website? I attempted to use a while() loop, but it ended up displaying vertically without using a table. I suspect this page utilizes thumbnails. What I aim for is to have the it ...