I wrote up a code designed to add two numbers and it keeps returning a NaN when I ask for an answer, I am fairly new but would like to know why this code in particular does not work so I can make sure I don't make the mistake again.
HTML
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>April23</title>
</head>
<body>
<!--Top Portion-->
<div class="container1">
<div class="calculator">
<label for="num1" id="num1">Enter First Number </label>
<input type="text" id="number0" name=num1 size=10>
</div>
<div class="calculator">
<label for="num2" id="num2">Enter Second Number</label>
<input type="text" id="number1" name=num1 size=10>
</div>
<div class="calculator2" id="button">
<button id="btn">Get Result</button>
</div>
<div class="calculator">
<label for="num2" id="sum"> Sum </label>
<input type="text" id="number" name=num1 size=10>
</div>
</div>
<div class="container1" id="c2"></div>
<div class="container1"></div>
</body>
<script src="main.js"></script>
</html>
JavaScript
/*this portion is to check if the blank input boxes are filled or not*/
const num1 = document.querySelector('#number0');
const num2 = document.querySelector('#number1');
/*this portion is to grab the value of the input boxes if they are filled*/
var number1=document.getElementById("number0").value;
var number2=document.getElementById("number1").value;
/*this portion is to convert the values into integers*/
x = parseInt(number1);
y = parseInt(number2);
const calc = document.querySelector(".calculator2");
calc.addEventListener('click', (e)=>
{
e.preventDefault();
if(num1.value==='' || num2.value ===''){
alert('please enter both numbers');
}
else{
alert(x+y);
}
}
)
So the first condition works and sends an alert box asking to input two numbers, the second condition returns a an Alert box with NaN instead of adding the two numbers
css
body{
margin: 0;;
/*background: url('image0.jpg') no-repeat; ;*/
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: thistle;
}
.container1{
position: relative;
height: 50vh;
background: rgb(39, 105, 160);
opacity: 0.9;
display: flex;
flex-direction: column;
justify-content: center;
gap: 2rem;
}
.calculator{
margin-left: 4rem;
}
#number{
margin-left: 7.5rem;
}
#number0{
margin-left: 1rem;
}
#c2{
background-color: rgb(196, 169, 169);
}
.calculator2{
margin-left: 4rem;
}
Take out the number after you click on the button not before. Everything else is great.
TIP: As you are adding the number there must be always a type number so it would be better to add type="number" on input so that the user cannot enter alphabets or special characters.
const calc = document.querySelector(".calculator2");
calc.addEventListener("click", (e) => {
e.preventDefault();
const x = document.querySelector("#number0").value;
const y = document.querySelector("#number1").value;
if (x === "" || y === "") {
alert("please enter both numbers");
} else {
alert(parseInt(x) + parseInt(y));
}
});
body {
margin: 0;
;
/*background: url('image0.jpg') no-repeat; ;*/
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: thistle;
}
.container1 {
padding: 2rem;
position: relative;
height: 50vh;
background: rgb(39, 105, 160);
opacity: 0.9;
display: flex;
flex-direction: column;
justify-content: center;
gap: 2rem;
}
.calculator {
margin-left: 4rem;
}
#number {
margin-left: 7.5rem;
}
#number0 {
margin-left: 1rem;
}
#c2 {
background-color: rgb(196, 169, 169);
}
.calculator2 {
margin-left: 4rem;
}
<div class="container1">
<div class="calculator">
<label for="num1" id="num1">Enter First Number </label>
<input type="number" id="number0" name=num1 size=10>
</div>
<div class="calculator">
<label for="num2" id="num2">Enter Second Number</label>
<input type="number" id="number1" name=num1 size=10>
</div>
<div class="calculator2" id="button">
<button id="btn">Get Result</button>
</div>
<div class="calculator">
<label for="num2" id="sum"> Sum </label>
<input type="text" id="number" name=num1 size=10>
</div>
</div>
<div class="container1" id="c2"></div>
<div class="container1"></div>
Related
I have this input field
<input name="question"/> I want to call IsEmpty function when submit clicking submit button.
I tried the code below but did not work.
any advice?
function IsEmpty() {
if (document.form.question.value == "") {
alert("empty");
}
return;
}
Question: <input name="question" /> <br/>
<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if ((a == null || a == "") && (b == null || b == "") && (c == null || c == "") && (d == null || d == "")) {
alert("Please Fill In All Required Fields");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():
function isEmpty(str) {
return !str.trim().length;
}
Example:
const isEmpty = str => !str.trim().length;
document.getElementById("name").addEventListener("input", function() {
if( isEmpty(this.value) ) {
console.log( "NAME is invalid (Empty)" )
} else {
console.log( `NAME value is: ${this.value}` );
}
});
<input id="name" type="text">
See the working example here
You are missing the required <form> element. Here is how your code should be like:
function IsEmpty() {
if (document.forms['frm'].question.value === "") {
alert("empty");
return false;
}
return true;
}
<form name="frm">
Question: <input name="question" /> <br />
<input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
Add an id "question" to your input element and then try this:
if( document.getElementById('question').value === '' ){
alert('empty');
}
The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.
See #Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
You can loop through each input after submiting and check if it's empty
let form = document.getElementById('yourform');
form.addEventListener("submit", function(e){ // event into anonymous function
let ver = true;
e.preventDefault(); //Prevent submit event from refreshing the page
e.target.forEach(input => { // input is just a variable name, e.target is the form element
if(input.length < 1){ // here you're looping through each input of the form and checking its length
ver = false;
}
});
if(!ver){
return false;
}else{
//continue what you were doing :)
}
})
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
if(document.getElementById("question").value == "")
{
alert("empty")
}
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
Customizing the input message using HTML validation when clicking on Javascript button
function msgAlert() {
const nameUser = document.querySelector('#nameUser');
const passUser = document.querySelector('#passUser');
if (nameUser.value === ''){
console.log('Input name empty!');
nameUser.setCustomValidity('Insert a name!');
} else {
nameUser.setCustomValidity('');
console.log('Input name ' + nameUser.value);
}
}
const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
.container{display:flex;max-width:960px;}
.w-auto {
width: auto!important;
}
.p-3 {
padding: 1rem!important;
}
.align-items-center {
-ms-flex-align: center!important;
align-items: center!important;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.d-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.d-inline-block {
display: inline-block!important;
}
.col {
-ms-flex-preferred-size: 0;
flex-basis: 0;
-ms-flex-positive: 1;
flex-grow: 1;
max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
margin-right: .5rem!important;
}
label {
font-family: "Oswald", sans-serif;
font-size: 12px;
color: #007081;
font-weight: 400;
letter-spacing: 1px;
text-transform: uppercase;
}
label {
display: inline-block;
margin-bottom: .5rem;
}
.x-input {
background-color: #eaf3f8;
font-family: "Montserrat", sans-serif;
font-size: 14px;
}
.login-input {
border: none !important;
width: 100%;
}
.p-4 {
padding: 1.5rem!important;
}
.form-control {
display: block;
width: 100%;
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
overflow: visible;
margin: 0;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
padding-right: 5px;
padding-left: 5px;
}
.col-lg-12 {
-ms-flex: 0 0 100%;
flex: 0 0 100%;
max-width: 100%;
}
.mt-1, .my-1 {
margin-top: .25rem!important;
}
.mt-2, .my-2 {
margin-top: .5rem!important;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
cursor: pointer;
}
.btn-petroleo {
background-color: #007081;
color: white;
font-family: "Oswald", sans-serif;
font-size: 12px;
text-transform: uppercase;
padding: 8px 30px;
letter-spacing: 2px;
}
.btn-xg {
padding: 20px 100px;
width: 100%;
display: block;
}
.btn {
display: inline-block;
font-weight: 400;
color: #212529;
text-align: center;
vertical-align: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-color: transparent;
border: 1px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
-webkit-writing-mode: horizontal-tb !important;
text-rendering: auto;
color: -internal-light-dark(black, white);
letter-spacing: normal;
word-spacing: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: textfield;
background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
-webkit-rtl-ordering: logical;
cursor: text;
margin: 0em;
font: 400 13.3333px Arial;
padding: 1px 2px;
border-width: 2px;
border-style: inset;
border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
border-image: initial;
}
<div class="container">
<form name="myFormLogin" class="w-auto p-3 mw-10">
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="nameUser">Usuário</label><br>
<input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
name="nameUser" placeholder="Name" required>
</div>
</div>
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="passUser">Senha</label><br>
<input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
name="passUser" placeholder="Password" required>
<div class="help">Esqueci meu usuário ou senha</div>
</div>
</div>
<div class="form-row d-flex align-items-center">
<div class="col-lg-12 my-1 mt-2 mb-2">
<button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
</div>
</div>
<div class="form-row align-items-center d-flex">
<div class="col-lg-12 my-1">
<div class="nova-conta">Ainda não é cadastrado? Crie seu acesso</div>
</div>
</div>
</form>
</div>
My solution below is in es6 because I made use of const if you prefer es5 you can replace all const with var.
const str = " Hello World! ";
// const str = " ";
checkForWhiteSpaces(str);
function checkForWhiteSpaces(args) {
const trimmedString = args.trim().length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
// If the browser doesn't support the trim function
// you can make use of the regular expression below
checkForWhiteSpaces2(str);
function checkForWhiteSpaces2(args) {
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
function checkStringLength(args) {
return args > 0 ? "not empty" : "empty string";
}
<pre>
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form>
</pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js file
Combining all the approaches we can do something like this:
const checkEmpty = document.querySelector('#checkIt');
checkEmpty.addEventListener('input', function () {
if (checkEmpty.value && // if exist AND
checkEmpty.value.length > 0 && // if value have one charecter at least
checkEmpty.value.trim().length > 0 // if value is not just spaces
)
{ console.log('value is: '+checkEmpty.value);}
else {console.log('No value');
}
});
<input type="text" id="checkIt" required />
Note that if you truly want to check values you should do that on the server, but this is out of the scope for this question.
The following code worked for me perfectly:
<form action = "dashboard.php" onsubmit= "return someJsFunction()">
<button type="submit" class="button" id = "submit" name="submit" >Upload to live listing</button>
</form>
<script type="text/javascript">
function someJsFunction(){
const input = document.getElementById('input1');
if(input.value === ""){
alert ("no input?"); // This will prevent the Form from submitting
return false;
}else{
return true; // this will submit the form and handle the control to php.
}
}
</script>
I'm making a calculator that will take inputs from a survey form and then push results to an object so I can display it on other parts of the site and use chart.js
However, I can't get the first calculation to work. My first function is to calculate the 30% saving of monthly gas spend (gas) and to subtract the saving from a monthly payment (price). I'm getting NaN in the console when the site loads even before clicking the button which has the eventlistener assigned to it.
Where am I going wrong?
P.S I haven't made the form responsive yet so it will need to be viewed in a full browser.
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc());
function calc() {
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
<html>
<head>
</head>
<body>
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
</body>
</html>
calculate.addEventListener('click', calc());
to
calculate.addEventListener('click', calc);
the calc() with parentheses will execute the function directly, whilst without it will only be called upon.
Also, you should add an event prevent default to not having the page refreshed.
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc);
function calc(event) {
// Prevent page refresh.
event.preventDefault();
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
I have tried to solve the issue: Please check
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc);
function calc() {
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
<html>
<head>
</head>
<body>
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
</body>
</html>
Hope, it will help you
Step #1
I added jquery reference in the head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Step #2
I added onclick event to call calc() function
Calculate
Step #3
I added this script now it's working fine
function calc() {
debugger
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
What I understand your are not properly calling the event that's why NAN(Not a Number) is appearing in the console and the second thing you asked in the comment about round off it is very simple
https://www.w3schools.com/JSREF/jsref_round.asp
please check this link it will help you
First off what changed is I added two new divs and assigned it an id class of "order" and one "menuOutput". Ever since then my CSS within the div id="menuOutput" has disappeared. How do I get my CSS styles back whilst not changing how my js code works? I know the new additions of the div are the problem but please tell me how to keep my styles with the new code?
<body>
<div id="order"></div>
<div id="menuOutput">
<h1 class="menu">Menu</h1>
<div class="grid">
<div class="two">
<h2>Pizza by the slice ($2)</h2>
<input type="number" id="qty_slice of pizza">
<h2>Toppings</h2>
<p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
<p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
<p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
<p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
</div>
<div class="one">
<h2>Sides</h2>
<p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
<p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
<p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
<p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
</div>
<div class="three">
<h2>Drinks</h2>
<div>
<p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
<p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
<p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
</div><hr>
<p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
<p class="titles">Water($1.25):</p> <input type="number" id="qty_water">
</div>
</div><br>
</div>
<div class="button">
<button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<script src="./run.js"></script>
</body>
------------------------------------JS---------------------------
//get menu from api
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
"pepperoni": ".25",
"meatballs": ".35",
"mushrooms": ".40",
"olives": ".20"
},
"sides": {
"potato salad": "1.25",
"hummus": "2.50",
"caesar salad": "3.50",
"garden salad": "2.25"
},
"drinks": {
"soda": {
"small": "1.95",
"medium": "2.20",
"large": "2.50"
},
"juice": "2.00",
"water": "1.25"
}
}
}
*/
getJSON('https://mm214.com/menu.php', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
var content = '';
for (x in data.menu){
if (typeof(data.menu[x]) == 'object'){
for (y in data.menu[x]) {
if (typeof(data.menu[x][y]) == 'object'){
for (z in data.menu[x][y]) {
content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
}
}
else {
content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
}
}//closes y in data
}
else
{
content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';
}//else for data.menu[x] if not an object
}
}//closes outer for loop
//localStorage only stores strings! Stringify turns objects into strings!
//parse converts JSON strings to objects that can be looped around
document.getElementById("menuOutput").innerHTML = content;
localStorage.setItem('order',JSON.stringify(data));
console.log(a + ':' + order[a]);
var order = JSON.parse(localStorage.getItem('order'));
console.log(typeof(order));
for (a in order){
}
});
function storeOrder(){
var pizzaqty = document.getElementById('qty_slice of pizza').value;
localStorage.setItem('pizza',pizzaqty);
var price = pizzaqty * 2;
}
function retrieveOrder(){
var pizzaordered = localStorage.getItem('pizza');
}
//output html
//
//document.getElementById("menuOutput").innerHTML = "Here is the menu: <br>" + data.menu;
//why in't this working?
//style menu for ordering
//save order as json string
//save in local storage
//your order button
//onclick: show order
document.getElementById('order').innerHTML = localStorage.getItem('order1');
------------------CSS------------------------------
#import url('https://fonts.googleapis.com/css2?
family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght#300&display=swap');
.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
}
.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}
input[type="number"] {
width: 40px;
}
.menu {
text-align: center;
}
.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
}
.titles {
font-family: 'Bree Serif', serif;
}
.pizza {
text-align: center;
color: tomato;
background-color: teal;
}
.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}
.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}
.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}
h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
The issue, I suspect is this line:
document.getElementById("menuOutput").innerHTML = content;
This basically says everything between the div with id "menuOutput" should now be the html in your content variable.
But nowhere in your content variable are you specifying the .grid, .one, .two, .three div classes.
Inspect the source code of the page: does <div class="two"> exist?
First of all, remember you can't have two identical ids in one page so you have to remove one of divs with id=order (I removed the one at the top). second, it seems you have added your classes in id attribute. we have two attributes for each element, id and class. you can add multiple classes for one element (e.g class="green blue red"), but you must have only one id which is unique in your page and can't include white spaces. (e.g id="blue_red"). at the end, I edited your code and removed the pizza from id and add it to the class and also corrected the values you have assigned to the elements and your css works fine again. you can run the snippet to see the result. wish it helps you:)
#import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght#300&display=swap');
.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
}
.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}
input[type="number"] {
width: 40px;
}
.menu {
text-align: center;
}
.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
}
.titles {
font-family: 'Bree Serif', serif;
}
.pizza {
text-align: center;
color: tomato;
background-color: teal;
}
.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}
.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}
.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}
h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
<div id="menuOutput">
<h1 class="menu">Menu</h1>
<div class="grid">
<div class="two">
<h2>Pizza by the slice ($2)</h2>
<input type="number" class="pizza" id="qty_slice_of_pizza">
<h2>Toppings</h2>
<p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
<p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
<p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
<p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
</div>
<div class="one">
<h2>Sides</h2>
<p class="titles">Potato Salad($1.25):</p> <input type="number" class="salad" id="qty_potato_salad">
<p class="titles">Humus($2.50):</p> <input type="number" class="salad" id="qty_hummus">
<p class="titles">Caesar Salad($3.50):</p> <input type="number" class="salad" id="qty_caesar_salad">
<p class="titles">Garden Salad($2.25):</p> <input type="number" class="salad" id="qty_garden_salad">
</div>
<div class="three">
<h2>Drinks</h2>
<div>
<p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
<p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
<p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
</div>
<hr/>
<p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
<p class="titles">Water($1.25):</p> <input type="number" id="qty_water">
</div>
</div>
<br/>
</div>
<div class="button">
<button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
The root cause of the problem is due to the div tags getting mixed up.
Here are the steps to resolve the problem:
Move the div tag meant for menu-output to the bottom of the page and add closure to it immediately.
Remove the duplicate div tags with same ID (menuOutput, order).
Here is the working example with the div tags adjusted and duplicate divs removed:
<html>
<head>
<title>Menu - demo</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght#300&display=swap');
.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
}
.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}
input[type="number"] {
width: 40px;
}
.menu {
text-align: center;
}
.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
}
.titles {
font-family: 'Bree Serif', serif;
}
.pizza {
text-align: center;
color: tomato;
background-color: teal;
}
.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}
.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}
.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}
h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
</style>
</head>
<body>
<div id="order">
<h1 class="menu">Menu</h1>
<div class="grid">
<div class="two">
<h2>Pizza by the slice ($2)</h2>
<input type="number" id="qty_slice_of_pizza" />
<h2>Toppings</h2>
<p class="titles">Per Pepperoni($0.25):</p>
<input type="number" id="qty_pepperoni">
<p class="titles">Per Meatball($0.35):</p>
<input type="number" id="qty_meatballs">
<p class="titles">Per Mushroom($0.40):</p>
<input type="number" id="qty_mushrooms">
<p class="titles">Per Olive($0.20):</p>
<input type="number" id="qty_olives">
</div>
<div class="one">
<h2>Sides</h2>
<p class="titles">Potato Salad($1.25):</p>
<input type="number" id="qty_potato_salad">
<p class="titles">Humus($2.50):</p>
<input type="number" id="qty_hummus">
<p class="titles">Caesar Salad($3.50):</p>
<input type="number" id="qty_caesar_salad">
<p class="titles">Garden Salad($2.25):</p>
<input type="number" id="qty_garden_salad">
</div>
<div class="three">
<h2>Drinks</h2>
<p class="titles">Small Soda($1.95):</p>
<input type="number" id="qty_small">
<p class="titles">Medium Soda($2.20):</p>
<input type="number" id="qty_medium">
<p class="titles">Large Soda($2.50):</p>
<input type="number" id="qty_large">
<p class="titles">Juice($2.00):</p>
<input type="number" id="qty_juice">
<p class="titles">Water($1.25):</p>
<input type="number" id="qty_water">
</div>
</div>
<br>
</div>
<div class="button">
<button type="button" id="submitOrder">Review Order</button>
</div>
<div id="menuOutput"></div>
<script>
//get menu from api
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('https://mm214.com/menu.php', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
var content = '';
for (x in data.menu){
if (typeof(data.menu[x]) == 'object'){
for (y in data.menu[x]) {
if (typeof(data.menu[x][y]) == 'object'){
for (z in data.menu[x][y]) {
content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
}
}
else {
content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
}
}//closes y in data
}
else
{
content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';
}//else for data.menu[x] if not an object
}
}//closes outer for loop
//localStorage only stores strings! Stringify turns objects into strings!
//parse converts JSON strings to objects that can be looped around
document.getElementById("menuOutput").innerHTML = content;
localStorage.setItem('order',JSON.stringify(data));
console.log(a + ':' + order[a]);
var order = JSON.parse(localStorage.getItem('order'));
console.log(typeof(order));
for (a in order){
}
});
function storeOrder(){
var pizzaqty = document.getElementById('qty_slice of pizza').value;
localStorage.setItem('pizza',pizzaqty);
var price = pizzaqty * 2;
}
function retrieveOrder(){
var pizzaordered = localStorage.getItem('pizza');
}
</script>
</body>
</html>
Output:
So I working on my integration of JS into my HTML and I want my web page to look some what presentable for a low level programmer. I've tried putting different divisions around and image (so two on the left vertically aligned and then an image the is the height of them combined in the gap on the right to fill the rest of that row.
I've tried the normal method of:
#insertDivIdHere{
float:left;
}
#otherDivIdHere{
float:left;
}
#insertImgIdHere{
float:left;
}
This method ends up with some weird formatting issues where the divisions overlap and the objects (ie buttons and text boxes) disappear and the image is to low.
Here is the HTML and CSS if you want to try it out (but I've left out my JS because I see no point in sharing it:
#header{
font-size: 16px;
background-color:lightsteelblue;
padding:12px;
text-align:center;
}
#form{
height: 30px;
width: 100px;
}
#formdiv {
background-color: lightcyan;
padding:12px;
height: 200px;
width:300px;
float: left;
}
#ageRange{
height: 30px;
width: 120px;
}
#ageRangeDiv{
background-color: lightgrey;
padding:12px;
height:140px;
width:300px;
float: left;
}
#creds{
border-radius: 5%;
box-shadow: lightskyblue;
font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
position: relative;
padding:3px;
}
#age{
border-radius: 5%;
box-shadow: lightskyblue;
font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
position: relative;
padding:3px;
}
#image{
width: auto;
height: 340px;
float:left;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:600,700"rel="stylesheet">
<title>Intergration</title>
<script src="script.js"></script>
</head>
<body>
<div id="header">
<h1>Web intergration</h1>
</div>
<div>
<div id="formdiv" name="formdiv">
<form id="form" name="form">
First Name <input type="text" name="firstName" ><br>
<br>
Last Name <input type="text" name="lastName" ><br>
<br>
Email <input type="email" name="email"><br>
</form>
<br><br><br><br><br><br><br>
<button type="button" id="creds" onclick="validCreds()">Confirm</button>
</div>
<div id="ageRangeDiv">
<form id="ageRange" name="ageRange">
<input type="radio" name="R1" id="U13" checked>Under 13 <br>
<input type="radio" name="R1" id="U18">13-18 <br>
<input type="radio" name="R1" id="U30">19-30 <br>
<input type="radio" name="R1" id="U50">31-50 <br>
<input type="radio" name="R1" id="O50">Over 50 <br>
</form>
<br><br><br><br>
<button type="button" id="age" onclick="validAge()">Confirm</button>
</div>
<div>
<img src="eve.jpg" id="image">
</div>
</div>
</body>
</html>
This is an example of how to use the inline-flex to align your content i hope you can modify them to do your layout.
#media only screen and (min-width: 600px) {
.container {
display: inline-flex;
}
.container div {
border: 1px solid red;
padding: 1em;
margin: 1em;
}
.container>div+div {
margin: auto;
}
}
#media only screen and (max-width: 600px) {
.container div:not(first-child) {
border: 1px solid red;
}
}
<div class="container">
<div>
<div>
1
</div>
<div>
2
</div>
</div>
<div>
3
</div>
</div>
I am new to programming using JavaScript. How do I repeat a string value retrieved from an <input type="text"> element value, repeat the string by the number retrieved from a sibling <input> element, then set the .innerHTML of a <div> element to the resulting repeated string using JavaScript? I have tried the below approach, which did not return expected result. What am I doing wrong at my current attempt? Is there a simpler way to achieve the expected result?
function repeatWord(str, num) {
num = Number(num);
var result = '';
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
return result;
}
</script>
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #D3D3D3;
font-family: arial;
text-align: right;
color: #008B8B;
}
#contentwrap {
border: 8px #800000 solid;
padding: 20px;
width: 600px;
border-radius: 25px;
text-align: right;
background: white;
margin: 40px auto 0px auto;
}
#formwrap {
text-align: center;
margin: 0px 0px 60px 0px;
min-height: 300px;
}
#title {
font-size: 2.2em;
border-bottom: 7px #008B8B double;
padding: 10px 0px 10px 0px;
color: #008B8B;
text-align: center;
}
#formtext {
text-align: center;
margin-top: 5px;
}
.formfield {
text-align: center;
margin: 5px 20px 10px 20px;
}
#button {
border-radius: 20px;
}
#results {
font-size: 1em;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="title">Fun with Loops</div> <br />
<div id="formwrap">
<form>
<div id="formtext">Enter any word</div>
<input type="text" id="word" class="formfield" size="20" /> <br />
<div id="formtext">Enter number of times to repeat word</div>
<input type="text" id="repeatnum" class="formfield" size="20" /> <br />
<input type="button" value="Show Output" id="button" onClick="repeatWord()" />
</form>
<div id="results"></div>
</div>
</div>
</body>
</html>
<html>
<head>
<title></title>
<script type="text/javascript">
function repeatWord(str, num) {
num = Number(num);
var result = '';
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
return result;
}
</script>
<style type="text/css">
body {
background-color: #D3D3D3;
font-family: arial;
text-align: right;
color: #008B8B;
}
#contentwrap {
border: 8px #800000 solid;
padding: 20px;
width: 600px;
border-radius: 25px;
text-align: right;
background: white;
margin: 40px auto 0px auto;
}
#formwrap {
text-align: center;
margin: 0px 0px 60px 0px;
min-height: 300px;
}
#title {
font-size: 2.2em;
border-bottom: 7px #008B8B double;
padding: 10px 0px 10px 0px;
color: #008B8B;
text-align: center;
}
#formtext {
text-align: center;
margin-top: 5px;
}
.formfield {
text-align: center;
margin: 5px 20px 10px 20px;
}
#button {
border-radius: 20px;
}
#results {
font-size: 1em;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="title">Fun with Loops</div> <br />
<div id="formwrap">
<form>
<div id="formtext">Enter any word</div>
<input type="text" id="word" class="formfield" size="20" /> <br />
<div id="formtext">Enter number of times to repeat word</div>
<input type="text" id="repeatnum" class="formfield" size="20" /> <br />
<input type="button" value="Show Output" id="button" onClick="repeatWord()" />
</form>
<div id="results"></div>
</div>
</div>
</body>
</html>
The function repeatWord returns expected result.
The issue is that you do not pass any parameters to the function, the return value from the function is not further processed. The DOM elements are not referenced within repeatWord function call. No element has .textContent or .innerHTML set using return value of repeatWord.
Note, you can use console.log() to check a value within a function call, or the return value of a function. For example, console.log(result). See also What is the scope of variables in JavaScript?.
You can substitute input type="number" forinput type="text"as#repeatnumelement, withminattribute set to0,maxattribute set to10`, or other positive number value, as a positive number would appear to be expected value of the element.
Define variables to reference elements having ids word, repeatnum, results to reference the elements within repeatWord function call.
Get the .values from #word and #repeatnum elements; set str as #word .value, set num with #repeatnum .valueAsNumber passed to Number constructor.
At completion of while loop, set #results .textContent to result.
<div id="contentwrap">
<div id="title">Fun with Loops</div>
<br />
<div id="formwrap">
<form>
<div id="formtext">Enter any word</div>
<input type="text" id="word" class="formfield" size="20" />
<br />
<div id="formtext">Enter number of times to repeat word</div>
<input type="number" min="0" max="10" id="repeatnum" class="formfield" size="20" />
<br />
<input type="button" value="Show Output" id="button" onClick="repeatWord()" />
</form>
<br>
<div id="results"></div>
</div>
</div>
<script>
var word = document.getElementById("word");
var number = document.getElementById("repeatnum");
var results = document.getElementById("results");
function repeatWord() {
// set `num` to `number` `.valueAsNumber`
num = number.valueAsNumber;
str = word.value; // set `str` to `word` `.value`
var result = "";
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
// set `results` `.textContent` to `result`
results.textContent = result;
}
</script>