i cant pass the variable in alert - javascript

on the button click of calculate ; i want to calculate all the cost.
i'm trying btn the alert is not working on the click.
i'm trying without the variable it is working.
but when i calculate all the values and pass it in the alert function .
it just doesn't display anything.
i have also used intParse() method to typecast..
Help Needed.
Much appreciated
function milkHandler() {
var tempMilk =document.orderForm.milk.value;
var milkTotal = tempMilk * 3.19;
console.log(milkTotal);
}
function eggHandler() {
var tempEgg =document.orderForm.eggs.value;
var eggTotal = tempEgg * 3.55;
console.log(eggTotal);
}
function breadHandler() {
var tempBread = document.orderForm.bread.value;
var breadTotal = tempBread * 3.49;
console.log(breadTotal);
}
function juiceHandler() {
var tempJuice =document.orderForm.juice.value;
var juiceTotal = tempJuice * 4.49;
console.log(juiceTotal);
}
function honeyHandler() {
var tempHoney = document.orderForm.honey.value;
var honeyTotal = tempHoney * 6.59;
console.log(honeyTotal);
}
function finish() {
var mainTotal = milkTotal+eggTotal+breadTotal+juiceTotal+honeyTotal;
alert(milkTotal);
}
<!DOCTYPE HTML>
<html>
<head>
<title>Shopping List</title>
<link href="css-pass/style.css" rel="stylesheet" type="text/css" media="all"/>
<!-- Custom Theme files -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Reset Password Form Responsive, Login form web template, Sign up Web Templates, Flat Web Templates, Login signup Responsive web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<!--google fonts-->
<!-- <link href='//fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900' rel='stylesheet' type='text/css'> -->
</head>
<style type="text/css">
.main-box
{
border: 0px solid;
height: 50px;
width: 100%;
}
.box-1
{
border: 0px solid;
height: 50px;
width: 20%;
float: left;
}
.box-2
{
border: 0px solid;
height: 50px;
width: 69%;
float: left;
}
.text
{
font-size: 20px;
color: #0086E7;
margin-top: 10px;
}
</style>
<body>
<!--element start here-->
<div class="elelment">
<h2>Grocery Order Form</h2>
<div class="element-main">
<h1>Type in the Quantities of each item you would like to purchase in the text box below</h1><br><br>
<form action="" method="post" name="orderForm" onsubmit="finish()">
<div class="main-box">
<div class="box-1">
<input type="number" name="milk" onChange = "milkHandler()" id="milk">
</div>
<div class="box-2">
<div class="text">Low Fat Milk [$3.19/Gallon]</div><br>
</div>
<div class="box-1">
<input type="number" name="eggs" onChange = "eggHandler()">
</div>
<div class="box-2">
<div class="text">Cage Free Organic Eggs [$3.55/Dozen]</div>
</div>
<div class="box-1">
<input type="number" name="bread" onChange = "breadHandler()">
</div>
<div class="box-2">
<div class="text">Whole White Bread [$3.49/Loaf]</div>
</div>
<div class="box-1">
<input type="number" name="juice" onChange = "juiceHandler()">
</div>
<div class="box-2">
<div class="text">Fresh Grape Juice [$4.49/Half Gallon]</div>
</div>
<div class="box-1">
<input type="number" name="honey" onChange = "honeyHandler()">
</div>
<div class="box-2">
<div class="text">Home Grown Honey [$6.59/Pint]</div>
</div>
</div>
<input type="submit" name="calculate" value="Calcuate" >
<input type="reset" name="calculate" value="Reset">
</form>
</div>
</div>
<div class="copy-right">
</div>
<!--element end here-->
</body>
<script src="script.js"></script>
</html>

You cannot use variables in one function and reuse them in another. You could use return. But a simpler way to do this is to put everything into one function.
function cal() {
var milk = document.getElementById('milk').value;
var butter = document.getElementById('butter').value;
var cheese = document.getElementById('cheese').value;
document.getElementById('result').innerHTML = milk*5 + butter*4 + cheese*3;
}
function res() {
document.getElementById('milk').value = 0;
document.getElementById('butter').value = 0;
document.getElementById('cheese').value = 0;
document.getElementById('result').innerHTML = "Value has been reset";
}
Milk: $5 <input type="number" id="milk" onchange="cal()" oninput="cal()"><br>
Butter: $4 <input type="number" id="butter" onchange="cal()" oninput="cal()"><br>
Cheese: $3 <input type="number" id="cheese" onchange="cal()" oninput="cal()"><br>
<button onclick="res()">Reset</button><br>
Total: <div id="result"></div>

The problem is all your variables are defined inside the functions causing them to cease existing when function ends.
You need to define these variables outside the functions.
var milkTotal = 0;
var eggTotal = 0;
var breadTotal = 0;
var juiceTotal = 0;
var honeyTotal = 0;
function milkHandler() {
var tempMilk =document.orderForm.milk.value;
milkTotal = tempMilk * 3.19;
console.log(milkTotal);
}
function eggHandler() {
var tempEgg =document.orderForm.eggs.value;
eggTotal = tempEgg * 3.55;
console.log(eggTotal);
}
function breadHandler() {
var tempBread = document.orderForm.bread.value;
breadTotal = tempBread * 3.49;
console.log(breadTotal);
}
function juiceHandler() {
var tempJuice =document.orderForm.juice.value;
juiceTotal = tempJuice * 4.49;
console.log(juiceTotal);
}
function honeyHandler() {
var tempHoney = document.orderForm.honey.value;
honeyTotal = tempHoney * 6.59;
console.log(honeyTotal);
}
function finish() {
var mainTotal = milkTotal+eggTotal+breadTotal+juiceTotal+honeyTotal;
alert(mainTotal);
}
<!DOCTYPE HTML>
<html>
<head>
<title>Shopping List</title>
<link href="css-pass/style.css" rel="stylesheet" type="text/css" media="all"/>
<!-- Custom Theme files -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Reset Password Form Responsive, Login form web template, Sign up Web Templates, Flat Web Templates, Login signup Responsive web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<!--google fonts-->
<!-- <link href='//fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900' rel='stylesheet' type='text/css'> -->
</head>
<style type="text/css">
.main-box
{
border: 0px solid;
height: 50px;
width: 100%;
}
.box-1
{
border: 0px solid;
height: 50px;
width: 20%;
float: left;
}
.box-2
{
border: 0px solid;
height: 50px;
width: 69%;
float: left;
}
.text
{
font-size: 20px;
color: #0086E7;
margin-top: 10px;
}
</style>
<body>
<!--element start here-->
<div class="elelment">
<h2>Grocery Order Form</h2>
<div class="element-main">
<h1>Type in the Quantities of each item you would like to purchase in the text box below</h1><br><br>
<form action="" method="post" name="orderForm" onsubmit="finish()">
<div class="main-box">
<div class="box-1">
<input type="number" name="milk" onChange = "milkHandler()" id="milk">
</div>
<div class="box-2">
<div class="text">Low Fat Milk [$3.19/Gallon]</div><br>
</div>
<div class="box-1">
<input type="number" name="eggs" onChange = "eggHandler()">
</div>
<div class="box-2">
<div class="text">Cage Free Organic Eggs [$3.55/Dozen]</div>
</div>
<div class="box-1">
<input type="number" name="bread" onChange = "breadHandler()">
</div>
<div class="box-2">
<div class="text">Whole White Bread [$3.49/Loaf]</div>
</div>
<div class="box-1">
<input type="number" name="juice" onChange = "juiceHandler()">
</div>
<div class="box-2">
<div class="text">Fresh Grape Juice [$4.49/Half Gallon]</div>
</div>
<div class="box-1">
<input type="number" name="honey" onChange = "honeyHandler()">
</div>
<div class="box-2">
<div class="text">Home Grown Honey [$6.59/Pint]</div>
</div>
</div>
<input type="submit" name="calculate" value="Calcuate" >
<input type="reset" name="calculate" value="Reset">
</form>
</div>
</div>
<div class="copy-right">
</div>
<!--element end here-->
</body>
<script src="script.js"></script>
</html>

Related

html & javascript enter button redirects to error page - otherwise duplicates text to chat (only when enter is pressed)

Whenever I click on the enter button, it seems the page either shows me
Bad Request
Did not attempt to load JSON data because the request Content-Type was not 'application/json'.
or rarely if enter is pressed it creates duplicates each chat by itself and adds it to the div
I have removed the key event of enter but for some odd reason the enter function still works, I presume this is due to bootstrap but im not too certain.
<!DOCTYPE html>
<html lang="en" style="height: 500px">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lexend" rel="stylesheet" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://www.unpkg.com/spltjs#1.1.0"></script>
<script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeit/5.0.2/typeit.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
<button type="button" class="btn btn-light" style="height:34px">click me</button>
<p style="color:white; font-family: Lexend;font-size: 15px;font-weight: 400;text-align: center;">AI for a healthier you</p>
<button type="button" class="btn btn-light" style="height:34px">click me</button>
</nav>
<br>
<center>
<div class="container" style="background-color:white ; border-radius: 20px;height:80%;-webkit-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);-moz-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);">
<p style="color:black" id="hello"></p>
<form method="post">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" value="hello world" id="button">Submit</button>
</form>
</div>
</div>
</div>
</center>
<script>
document.getElementById("button").addEventListener("click", insertText);
// CREATES A DIV AND SENDS THE USERS TEXT
function insertText() {
let div = document.createElement("div");
let usertext = document.getElementById('textinput').value;
const usertext2 = 'Patient: ' + usertext;
let text = document.createTextNode(usertext2);
div.appendChild(text);
document.getElementById("hello").appendChild(div);
/////////////// submit JSON TO APP
var json_entry = usertext
fetch('/dashboard', {
method: 'POST',
body: JSON.stringify({
user_text: json_entry
}),
headers: {
'Content-Type': 'application/json'
}
});
let apiData;
fetch('/dashboard/api').then((response) => response.json()).then((data) => {
apiData = data;
let div = document.createElement('div');
let robot_reply = document.createTextNode(apiData);
div.appendChild(robot_reply);
document.getElementById("hello").appendChild(div);
});
////// ENTER BUTTON ////
///////////////////////
/////////////////////// allows the ability to hit the enter button
var input = document.getElementById("textinput");
}
</script>
</div>
</div>
</body>
</html>
When you hit enter, it triggers the submit event on the <form>, which will cause a page refresh. This is basically baked in browser functionality. Any enter keypress in a field inside a <form> tag, causes a form submission. If that form submission is not handled, it will attempt to POST the form to the current URL.
You need to attach everything to the submit event on the <form>, not the button click. And you also need to call e.preventDefault to prevent the browsers default form action handling.
Additionally, you need type="submit" on the button so the click on that button also submits the form.
Using form submit event is also better for accessibility. It means users can press enter in a field or click the button, and it will be handled.
<!DOCTYPE html>
<html lang="en" style="height: 500px">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lexend" rel="stylesheet" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://www.unpkg.com/spltjs#1.1.0"></script>
<script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeit/5.0.2/typeit.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
<button type="button" class="btn btn-light" style="height:34px">click me</button>
<p style="color:white; font-family: Lexend;font-size: 15px;font-weight: 400;text-align: center;">AI for a healthier you</p>
<button type="button" class="btn btn-light" style="height:34px">click me</button>
</nav>
<br>
<center>
<div class="container" style="background-color:white ; border-radius: 20px;height:80%;-webkit-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);-moz-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);">
<p style="color:black" id="hello"></p>
<form method="post" id="form">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" value="hello world" id="button">Submit</button>
</form>
</div>
</div>
</div>
</center>
<script>
document.getElementById("form").addEventListener("submit", insertText);
// CREATES A DIV AND SENDS THE USERS TEXT
function insertText(e) {
e.preventDefault();
let div = document.createElement("div");
let usertext = document.getElementById('textinput').value;
const usertext2 = 'Patient: ' + usertext;
let text = document.createTextNode(usertext2);
div.appendChild(text);
document.getElementById("hello").appendChild(div);
/////////////// submit JSON TO APP
var json_entry = usertext
fetch('/dashboard', {
method: 'POST',
body: JSON.stringify({
user_text: json_entry
}),
headers: {
'Content-Type': 'application/json'
}
});
let apiData;
fetch('/dashboard/api').then((response) => response.json()).then((data) => {
apiData = data;
let div = document.createElement('div');
let robot_reply = document.createTextNode(apiData);
div.appendChild(robot_reply);
document.getElementById("hello").appendChild(div);
});
////// ENTER BUTTON ////
///////////////////////
/////////////////////// allows the ability to hit the enter button
var input = document.getElementById("textinput");
}
</script>
</div>
</div>
</body>
</html>

How do I create output box for the calculator function?

I'm a completely beginner in Javascript and trying to create a simple program to calculate the area of a circle. I'm currently stuck on how to create an output box containing the variable area. Apologies if this is a dumb question, but I do appreciate any kind of help!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Circle Area Calculator</title>
</head>
<body>
<fieldset><h3><i>Enter radius of a circle:</i></h3>
<form name="circleForm" onsubmit="calc()">
<label for="name">Enter a number:</label><br>
<input type="number" name="radius" id="radius" placeholder="radius" required><br>
<button type="submit">Calculate Area</button>
<button type="reset">Reset value</button>
</form>
<div id="result">
<output name="result" onsubmit="result()">
</output>
</div>
</fieldset>
</body>
<script>
function calc() {
var radius = document.forms.circleForm.elements.namedItem("radius").value;
var area = (radius**2)*3.14
var calculate;
return area
document.getElementById("result").innerHTML = area;
}
</script>
</html>
Add an event listener to your button and run your calc function from there.
Using event.preventDefault() will prevent the browser from submitting the form and refreshing the page.
Setting the innerHTML of the result div is the right thing to do but you'd put it after your function returned a value, which was preventing it from being executed.
let calculate = document.getElementById('calculate');
calculate.addEventListener('click', () => {
event.preventDefault();
calc();
});
function calc() {
var radius = document.forms.circleForm.elements.namedItem("radius").value;
var area = (radius ** 2) * 3.14
var calculate;
document.getElementById("result").innerHTML = area;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Circle Area Calculator</title>
</head>
<body>
<fieldset>
<h3><i>Enter radius of a circle:</i></h3>
<form name="circleForm">
<label for="name">Enter a number:</label><br>
<input type="number" name="radius" id="radius" placeholder="radius" required><br>
<button id="calculate">Calculate Area</button>
<button type="reset">Reset value</button>
</form>
<div id="result">
</div>
</fieldset>
</body>
</html>
this way
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Circle Area Calculator</title>
<style>
form {
width : 20em;
}
legend {
font-size : 1.2em;
font-weight : bold;
font-style : italic;
padding : 0 .4em;
}
label {
font-size : .8em;
}
input,output {
display : block;
}
button {
margin : .8em .4em;
}
</style>
</head>
<body>
<form name="circle-form">
<fieldset>
<legend>Enter radius of a circle:</legend>
<label>Enter a number:</label>
<input type="number" name="radius" id="radius" placeholder="radius" required><br>
<button type="submit">Calculate Area</button>
<button type="reset">Reset value</button>
<output name="result"> </output>
</fieldset>
</form>
<script>
const circleForm = document.forms['circle-form'];
circleForm.onsubmit = e =>
{
e.preventDefault() // disable page submit ==> relaod page
circleForm.result.textContent = (circleForm.radius.valueAsNumber ** 2) * Math.PI
}
circleForm.onreset = e =>
{
circleForm.result.innerHTML = ' '
circleForm.radius.value = ''
}
</script>
</body>
</html>
Demo
const circleForm = document.forms['circle-form'];
circleForm.onsubmit = e =>
{
e.preventDefault() // disable page submit ==> relaod page
circleForm.result.textContent = (circleForm.radius.valueAsNumber ** 2) * Math.PI
}
circleForm.onreset = e =>
{
circleForm.result.innerHTML = ' '
}
form {
width : 20em;
}
legend {
font-size : 1.2em;
font-weight : bold;
font-style : italic;
padding : 0 .4em;
}
label {
font-size : .8em;
}
input,output {
display : block;
}
button {
margin : .8em .4em;
}
<form name="circle-form">
<fieldset>
<legend>Enter radius of a circle:</legend>
<label>Enter a number:</label>
<input type="number" name="radius" id="radius" placeholder="radius" required><br>
<button type="submit">Calculate Area</button>
<button type="reset">Reset value</button>
<output name="result"> </output>
</fieldset>
</form>

Did I correctly set-up my API for this weather app?

I am working with a weather app api and I am trying to display weather Data based off what the users inserts in the form. For some reason the data is not displaying. I have gone through the code 10 times, and I cant seem to find the error.
Can anyone take a look at point out where I have gone wrong?
Thank you
$(document).ready(function() {
$('submitWeather').click(function() {
var city = $('#city').val();
if (city != '') {
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=_MY_API_KEY_",
type: "GET",
dataType: "jsonp",
success: function(data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val('');
}
});
} else {
$("#error").html('Field cannot be empty');
}
});
});
function show(data) {
return '<h3><strong>Weather<strong>: ' + data.weather[0].main + ' </h3>' +
'<h3><strong>Weather<strong>: ' + data.weather[0].description + ' </h3>';
}
console.log('hello')
.mainArea {
background-color: lightgray;
}
.day1,
.day2,
.day3,
.day4,
.day5 {
width: 220px;
height: 200px;
background-color: blue;
position: relative;
color: white;
}
.input {
text-align: center;
}
input[type='text'] {
height: 50px;
width: 200px;
background: #e7e7e7;
}
input[type='submit'] {
height: 50px;
width: 100px;
background: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Weather Dashboard</title>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-light bg-light jumbotron">
<div class="navbar-brand">Weather Guide</a>
<!-- <form class="form-inline">
<input class="inputValue form-control mr-sm-2" type="text" placeholder="Search City" aria-label="Search">
<button class="button btn btn-outline-success my-2 my-sm-0" value="submit" type="submit">Search</button>
</form>-->
</nav>
<div class="container">
<div class="row">
<h3 class="text-center text-primary">Enter City Name</h3>
</div>
<div class='row form-group form-inline'>
<input tyepe='text' name='city' id="city" class="form-control" placeholder="city name">
<button id="submitWeather" class="btn btn-primary">Search</button>
</div>
<div id="show">
</div>
</div>
<!-- Main Content -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
$('submitWeather') should be $('#submitWeather')
Here's how to do it without jquery incase anybody wants it:
const getCity = () => document.querySelector('input#city').value || "austin"
document.querySelector("#getWeather").addEventListener('click', function () {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${getCity()}&units=metric&APPID=_MY_API_KEY_`
loadDataRequest(url, displayJSON)
})
function loadDataRequest(url, cb) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cb(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function displayJSON(xhttp) {
document.querySelector("#show").textContent = JSON.stringify(JSON.parse(xhttp.response), null, 2);
}
<input id="city" name="city" placeholder="city"/>
<button id="getWeather" type="button" >Get</button>
<div id="show" style="white-space:pre"></div>

How to add error Handling to check if the inputs are numbers in a separate function

I am looking to have the inputs only numbers and if its anything else then it will alert that you typed in a letter and it has to be in a different function. Also, it has to be in vanilla javascript and it is for a project and has to have 3 running functions that's why it has to be in a separate function.Thanks!
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta charset="utf-8">
<title>Tip Calc.</title>
<style>
html,body{
width:100%;
height:100%;
}
body{
margin:0px;
overflow-x:hidden;
background-color: #f9f8f4 !important
}
p{
font-size: 18px !important;
font-family: 'Raleway', sans-serif;
}
h1,h2,h3{
font-family: 'Raleway', sans-serif;
}
</style>
</head>
<body>
<div class="container">
<br>
<h1 class="text-center">Tip Calculator</h1>
<br><br>
<div class="row">
<div class="col-lg-6">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Total</label>
<input type="text" class="form-control" id="total" aria-describedby="emailHelp" placeholder="Enter Total Price">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Tip Percentage %</label>
<input type="text" class="form-control" id="percent" placeholder="Tip Percentage">
</div>
<button type="submit" class="btn btn-primary" id="btn">Submit</button>
</form>
</div>
<div class="col-lg-6">
<h2>Total Price:</h2><h3 id="totalprice"></h3>
</div>
</div>
</div>
<script>
window.addEventListener("DOMContentLoaded",init,false);
function init(){
document.getElementById("btn").addEventListener("click", getprice, false);
}//end init function
function getprice(e) {
e.preventDefault();
math();
// var totalpriceout = document.getElementById("totalprice").value = totalValue.toFixed(2);
}
function math(){
var numVal1 = Number(document.getElementById("total").value);
var numVal2 = Number(document.getElementById("percent").value) / 100;
var totalValue = numVal1 + (numVal1 * numVal2)
document.getElementById("totalprice").innerHTML = "$" + totalValue.toFixed(2);
}
</script>
</body>
</html>
The baseline of what you're looking for is parseFloat, i.e.
var foo = "abcdef"
var bar = "123456"
foo == parseFloat(foo)
->false
bar == parseFloat(bar)
->true
since this appears to be homework help I don't want to give too much away past that.
As stated here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat, parseFloat will return a floating point number parsed from the given value. If the value cannot be converted to a number, NaN is returned.
consider using Number.isNaN() in conjunction.
perhaps:
if (Number.isNaN(parseFloat(foo))) { //error handler } else { //regular action} –

How olx.com show form fields on category change and submit accordingly?

I want to know how to design post ad form like olx whose form fields changed on category change.
var subs = document.querySelectorAll(".sub");
function modeChanged() {
removeDisp();
var chooser = document.querySelector("#chooser").value;
if (chooser !== "") {
document.querySelector("." + chooser).style.display = "block";
}
}
removeDisp();
function removeDisp() {
for (var a = 0; a < subs.length; a++) {
subs[a].style.display = "none";
}
}
.sub {
margin-top: 10px;
}
label {
margin-top: 5px;
display: block !important;
}
label span {
width: 200px;
display: inline-block;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<select name="chooser" id="chooser" onchange="modeChanged()">
<option value="">Select</option>
<option value="home">Home</option>
<option value="shop">Shop</option>
<option value="car">Car</option>
</select>
<div class="sub home">
<label><span>Type Of Home:</span>
<input/>
</label>
<label><span>Price Range:</span>
<input/>
</label>
</div>
<div class="sub shop">
<label><span>Shop Size:</span>
<input/>
</label>
<label><span>Shop Area:</span>
<input/>
</label>
</div>
<div class="sub car">
<label><span>Car Modal:</span>
<input/>
</label>
<label><span>Date of purchase:</span>
<input/>
</label>
</div>
</body>
</html>
Check it

Categories

Resources