Specify user input render location in javascript - javascript

[I'm simply trying to make a form that allows you to select which box the user's name and password will display in. The code I have works fine but I'm curious to see how it could be refactored to be less repetitive. I thought of using a JS object but I'm not sure how to go about that in this instance. Any help would be appreciated! Here is a link to the CodePen: (https://codepen.io/TOOTCODER/pen/yLeagRq)
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Which Box?</title>
<style>
.square{
border: 1px solid black;
width: 15rem;
height: 15rem;
float: left;
}
#formContainer {
position: relative;
top: 16rem;
left: -45.5rem;
}
.boxTitle {
text-align: center;
margin-top: 1em;
}
.boxOutputContainer {
text-align: center;
}
</style>
</head>
<body>
<div class="square">
<h1 class="boxTitle">BOX1</h1>
<div class="boxOutputContainer">
<div id="b1NameOutput"></div>
<div id="b1PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX2</h1>
<div class="boxOutputContainer">
<div id="b2NameOutput"></div>
<div id="b2PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX3</h1>
<div class="boxOutputContainer">
<div id="b3NameOutput"></div>
<div id="b3PasswordOutput"></div>
</div>
</div>
<div id="formContainer">
<form>
<label for="name">Name:</label>
<input required type="text" id="name">
<label for="name">Password:</label>
<input required type="text" id="password">
<label for="boxSelect">Which box?</label>
<select id="boxSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" id="submitBtn">
</form>
</div>
<script>
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var b1NameOutput = document.querySelector("#b1NameOutput");
var b1PasswordOutput = document.querySelector("#b1PasswordOutput");
var b2NameOutput = document.querySelector("#b2NameOutput");
var b2PasswordOutput = document.querySelector("#b2PasswordOutput");
var b3NameOutput = document.querySelector("#b3NameOutput");
var b3PasswordOutput = document.querySelector("#b3PasswordOutput");
if(boxSelect.value == 1){
b1NameOutput.innerHTML = "<p>"+name.value+"</p>";
b1PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 2){
b2NameOutput.innerHTML = "<p>"+name.value+"</p>";
b2PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 3){
b3NameOutput.innerHTML = "<p>"+name.value+"</p>";
b3PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}});
</script>
</body>
</html>

I see someone beat me to the answer but here is another option that is easy to refactor.
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var nameId = `#b${boxSelect.value}NameOutput`;
var passwordId = `#b${boxSelect.value}PasswordOutput`;
var nameOutput = document.querySelector(nameId);
nameOutput.innerHTML = "<p>"+name.value+"</p>";
var passwordOutput = document.querySelector(passwordId);
passwordOutput.innerHTML = "<p>"+password.value+"</p>";
});

Related

form submitting 0 to database

I have an html form with item and amount entries and I want the values in them to be stored in local storage and xampp, I have succeeded in submiting to localstorage however the form submits nothing in xampp in a column for item and 0 in the column of amount
here is my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ICT specialists</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="app.css" />
<link rel="shortcut icon" href="ICT_Logo-01.png">
</head>
<body>
<h2>Daily transactions at ICT specialists</h2>
<div class="container">
<h4>Your balance</h4>
<h1 id="balance"></h1>
<div class="inc-exp-container">
<div>
<h4>income</h4>
<p id="money-plus" class="money plus"></p>
</div>
<div>
<h4>expense</h4>
<p id="money-minus" class="money minus"></p>
</div>
</div>
<h3>History</h3>
<div class="shows">
<ion-icon name="menu-outline" id="showLi"></ion-icon>
<ion-icon name="close-outline" id="hideLi"></ion-icon>
</div>
<ul id="list" class="list"></ul>
<h3>add new transation</h3>
<form action="sales.php" method="post" id="form">
<div class="form-control">
<label for="">date</label>
<input type="text" id="date" name="date">
</div>
<div class="form-control">
<label for="text">item</label>
<input type="text" id="text" name="item" placeholder="please enter the item..." autocomplete="off" />
</div>
<div class="form-control">
<label for="amount">amount <br />(negative=expense, positive=income)</label>
<input type="number" id="amount" name="amount" placeholder="please enter the amount..." autocomplete="off" />
</div>
<button class="btn" type="submit">Add transation</button>
</form>
</div>
<div class="footer">
<div class="footerTxt">copyright &copy <span id="dated">2022</span</div>
<div class="footerRyt">
ict specialists | sydotech
</div>
</div>
<style>
.footer{
display: flex;
justify-content: space-evenly;
width: 100%;
bottom: 0;
background: deepskyblue !important;
padding: 10px;
position: fixed;
}
.footer .footerTxt{
font-size: 1.2rem;
text-transform: capitalize;
font-weight: 500;
}
.footer .footerRyt a{
text-decoration: none;
font-size: 1.4rem;
color: #fff !important;
}
</style>
<ion-icon name="arrow-up-outline" id="icons"></ion-icon>
<script src="sales.js"></script>
<script type="module" src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.esm.js">
</script>
<script nomodule src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.js"></script>
</body>
</html>
here is my php
<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=sales','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if($_SERVER['REQUEST_METHOD']==='POST'){
$item = $_POST['item'];
$amount = $_POST['amount'];
$statement = $pdo->prepare("insert into transaction
(item,amount)
values (:item,:amount)");
$statement->bindValue(':item', $item );
$statement->bindValue(':amount', $amount );
$statement->execute();
header('Location: sales.html');
}
here is my javascript file
const balance = document.getElementById("balance");
const money_plus = document.getElementById("money-plus");
const list = document.getElementById("list");
const form = document.getElementById("form");
const text = document.getElementById("text");
const amount = document.getElementById("amount");
const money_minus = document.getElementById("money-minus");
let showLi = document.getElementById("showLi");
let hideLi = document.getElementById('hideLi');
const localStorageTransations = JSON.parse(localStorage.getItem("transations"));
let transations =
localStorage.getItem("transations") !== null ? localStorageTransations : [];
//add transation
function addTransation() {
// e.preventDefault();
if (text.value.trim() === "" || amount.value.trim() === "") {
text.placeholder = "PLEASE SOME TEXT";
text.style.backgroundColor = "#ccc";
text.style.fontWeight = 'bold';
amount.placeholder = "ENTER AMOUNT";
amount.style.backgroundColor = "#ccc";
amount.style.fontWeight = 'bold';
} else {
const transation = {
id: genenrateID(),
text: text.value,
amount: +amount.value,
};
transations.push(transation);
addTransationDOM(transation);
updateValues();
updateLocalStorage();
text.value = "";
amount.value = "";
}
}
//generate id
function genenrateID() {
return Math.floor(Math.random() * 100000000);
}
//add transations to dom list
function addTransationDOM(transation) {
//get sign
const sign = transation.amount < 0 ? "-" : "+";
const item = document.createElement("li");
//add class based on value
item.classList.add(transation.amount < 0 ? "minus" : "plus");
item.innerHTML = `${transation.text} <span>${sign}${Math.abs(transation.amount)}</span>
<button class="delete-btn" onclick="removeTransation(${transation.id})">x</button>`;
list.appendChild(item);
item.style.display="none";
hideLi.addEventListener('click',()=>{
item.style.display = 'none';
hideLi.style.display = "none";
showLi.style.display = "block";
});
showLi.addEventListener('click',()=>{
item.style.display = 'block';
hideLi.style.display = "block";
showLi.style.display = "none";
})
}
// ********hide list******
// ********hide list end******
//update the balance
function updateValues() {
const amounts = transations.map((transation) => transation.amount);
const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(0);
const income = amounts
.filter((item) => item > 0)
.reduce((acc, item) => (acc += item), 0)
.toFixed(0);
const expense = (
amounts.filter((item) => item < 0).reduce((acc, item) => (acc += item), 0) * -1).toFixed(0);
balance.innerText = `UgShs: ${total}`;
money_plus.innerText = `UgShs: ${income}`;
money_minus.innerText = `UgShs: ${expense}`;
}
//remove
function removeTransation(id) {
transations = transations.filter((transation) => transation.id !== id);
updateLocalStorage();
init();
}
//updatelocal storage
function updateLocalStorage() {
localStorage.setItem("transations", JSON.stringify(transations));
}
function init() {
list.innerHTML = "";
transations.forEach(addTransationDOM);
updateValues();
}
init();
form.addEventListener("submit", addTransation);
// *********date calculation********
let date =document.getElementById('date');
date.value = new Date().toDateString();
// *********ionicons*******88
let icon = document.getElementById('icons');
window.onscroll = ()=>{
if(window.scrollY >=100){
icon.style.display = 'block';
icon.style.position = 'fixed';
}else{
icon.style.display = 'none';
}
}
icon.addEventListener('click',()=>{
window.scrollTo({top:0, behavior:"smooth"})
})
let span11 = document.getElementById('dated');
span11.innerHTML = new Date().getFullYear();

I need help for my sign up form with javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I was doing doing a sign up form and it not includes back-end part. I almost done but right now ı have a problem within javascript part with Email confirmation thing. It's a simple thing, since ı will leave codes down here you will also see it. I've tryed something and still didn't deleted them. When you see those codes probably undurstand my problem. plesase help me with this
const container = document.querySelector(".container");
const Name = document.querySelector("#Name");
const Email = document.querySelector("#Email");
const Password = document.querySelector("#password");
const Password__Confirm = document.querySelector("#password-confirm");
const Submit = document.querySelector(".submit");
const bar = document.querySelectorAll(".bar");
const Notice = document.querySelectorAll(".notice");
const notice_1 = document.querySelector("#notice--1");
const notice_2 = document.querySelector("#notice--2");
const notice_3 = document.querySelector("#notice--3");
Submit.addEventListener("click", () => {
const nameLength = Name.value.length;
console.log(Email.value.split("#"));
const emailValue = Email.value.trim();
const [firstPart, email] = Email.value.split("#");
console.log(email);
const password = Password.value;
console.log(password);
const password_c = Password__Confirm.value;
console.log(nameLength);
Notice.forEach((notice) => {
notice.classList.add("hidden");
if (nameLength <= 1) {
notice_1.classList.remove("hidden");
console.log(Name.value);
//console.log(password);
}
//if (!(emailValue.includes("#"))) {
// nostice_2.classList.remove(".hidden");
//}
//if (!(email.includes("gmail.com")) ||
// !(email.includes("hotmail.com"))) {
// notice_2.classList.remove("hidden");
//}
if (password.length < 6 || !(password===password_c)) {
notice_3.classList.remove("hidden");
}
});
});
html{
padding: 0;
margin: 0;
}
.container{
position: absolute;
right: 40%;
top: 30%;
box-shadow: 5px 5px 30px 30px rgba(0, 0, 0, 0.1);
padding: 50px;
}
.notice{
color: red;
}
.hidden{
visibility: hidden;
}
<!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">
<link rel="stylesheet" href="style.css" />
<title>Confirmation</title>
</head>
<body>
<div class="container">
<form action="">
<label for="">Name</label><br>
<input class="bar" id="Name" type="text"><br>
<label for="">Email</label><br>
<input class="bar" id="Email" type="text"><br>
<label for="">Password</label><br>
<input class="bar" id="password" type="password"><br>
<label for="">Confirm Password</label><br>
<input class="bar" id="password-confirm" type="password"><br>
<input class="submit" type="button" value="Sing Up">
</form>
<ul class="warning">
<li class="notice hidden" id="notice--1">Name is required</li>
<li class="notice hidden" id="notice--2">Email is invalid</li>
<li class="notice hidden" id="notice--3">Password must be 6 character or more</li>
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
You looped through Notices, but added back .hidden to the notices. I made minor changes to your code. You will probably understand it when you see the code. Also, your variable notice_2 was misspelled.
const Name = document.querySelector("#Name");
const Email = document.querySelector("#Email");
const Password = document.querySelector("#password");
const Password__Confirm = document.querySelector("#password-confirm");
const Submit = document.querySelector(".submit");
const Notice = document.querySelectorAll(".notice");
Submit.addEventListener("click", () => {
const nameLength = Name.value.length;
const emailValue = Email.value.trim();
const [firstPart, email] = Email.value.split("#");
const password = Password.value;
const password_c = Password__Confirm.value;
Notice.forEach((notice) => {
notice.classList.add("hidden");
if (notice.id == 'notice--1' && nameLength <= 1) {
notice.classList.remove("hidden");
} else if (notice.id == 'notice--2') {
if (!(emailValue.includes("#"))) {
notice.classList.remove("hidden");
}
}
else if (notice.id == 'notice--3' && (password.length < 6 || !(password === password_c))) {
notice.classList.remove("hidden");
}
});
});
html {
padding: 0;
margin: 0;
}
.container {
padding: 1rem;
margin: 1rem;
box-shadow: 5px 5px 30px 30px rgba(0, 0, 0, 0.1);
}
.notice {
color: red;
}
.hidden {
display: none;
}
<div class="container">
<form action="">
<label for="">Name</label><br>
<input class="bar" id="Name" type="text"><br>
<label for="">Email</label><br>
<input class="bar" id="Email" type="text"><br>
<label for="">Password</label><br>
<input class="bar" id="password" type="password"><br>
<label for="">Confirm Password</label><br>
<input class="bar" id="password-confirm" type="password"><br>
<input class="submit" type="button" value="Sign Up">
</form>
<ul class="warning">
<li class="notice hidden" id="notice--1">Name is required</li>
<li class="notice hidden" id="notice--2">Email is invalid</li>
<li class="notice hidden" id="notice--3">Password must be 6 character or more</li>
</ul>
</div>

Why do I keep getting ReferenceError: * is not defined?

New to Javascript and I can't get the error message ReferenceError: calculateOrder is not defined to go away no matter what I try. I've moved my var out and back in tried different statements. Nothing of the knowledge I have so far is working. How can I get rid of this error message? Would appreciate any help or pointers I can get.
var cost = 750;
var pasta_prices = new Array();
pasta_prices["spaghetti"] = 0;
pasta_prices["fettucine"] = 50;
pasta_prices["fusilli"] = 75;
var sauce_prices = new Array();
sauce_prices["pomodoro"] = 0;
sauce_prices["bolognese"] = 50;
sauce_prices["alfredo"] = 100;
function getPastaPrice() {
var pastaPrice = 0;
var form = document.forms["myForm"];
var selectedPasta = myForm.elements["pastatype"];
for (var i = 0; i < selectedPasta.length; i++) {
if (selectedPasta[i].checked) {
pastaPrice = pasta_prices[selectedPasta[i].value];
break;
}
}
return pastaPrice;
}
function getSaucePrice() {
var saucePrice = 0;
var myForm = document.forms["myForm"];
var selectedSauce = myForm.elements["sauce"];
saucePrice = sauce_prices[selectedSauce.value];
return saucePrice;
}
function extrasPrice() {
var extraPrice = 0;
var myForm = document.forms["myForm"];
var includeSalad = myForm.elements["salad"];
var includeSticks = myForm.elements["sticks"];
if (includeSalad.checked == true) {
extraPrice = 200;
}
if (includeSticks.checked == true) {
extraPrice = 100;
}
return extraPrice;
}
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost / 100).toFixed(2));
return ordCost;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Costello Improved">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Costellos Pasta and Pizza</title>
<script language="JavaScript" type="text/javascript" src="costello.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
.col-md-12{
text-align: center;
font-size: 3em;
background-color: red;
}
.msg{
text-align:center;
font-size: 1.3em;
color: red;
}
.row{
margin-top: 10px;
border: 5px solid white;
background-color: silver;
padding: 10px;
}
.label{
text-align:center;
vertical-align:top;
}
#submitMessage{
transition: opacity 10s;
}
#cancel{
text-decoration: underline;
}
</style>
</head>
<body>
<form name="myForm" action="https://costello-pasta.glitch.me/order" id="myForm" method="POST" onsubmit="return calculateOrder()">
<div class="container">
<div class="row">
<div class="col-md-12" id="debug">Costello's Online Orders</div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta Bowl</div>
<div class="col-md-4" > (basic price: $7.50)</div>
<div class="col-md-4" ></div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta</div>
<div class="col-md-4" >
<div><input type="radio" name="pastatype" value="0" id="spaghetti"/>Spaghetti (no extra cost)</div>
<div><input type="radio" name="pastatype" value="50" id="fettucine"/>Fettucine (add 50 cents)</div>
<div><input type="radio" name="pastatype" value="75" id="fusilli"/>Fusilli (add 75 cents)</div>
</div>
<div class="col-md-4 msg" id="radioLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Sauce</div>
<div class="col-md-4" >
<select name="sauce" >
<option value="0" id="pomodoro">Pomodoro (no extra cost)</option>
<option value="50" id="bolognese">Bolognese (add 50 cents)</option>
<option value="100" id="alfredo">Alfredo (add $1.00)</option>
</select>
</div>
<div class="col-md-4" ></div>
</div>
<div class="row">
<div class="col-md-4 label">Extras</div>
<div class="col-md-4" >
<div><input type="checkbox" name="extras" value="200" id="salad"/>Side salad (add $2.00)</div>
<div><input type="checkbox" name="extras" value="100" id="sticks"/>Bread sticks (add $1.00)</div>
</div>
<div class="col-md-4" ></div>
</div>
<div class="row">
<div class="col-md-4 label">Name</div>
<div class="col-md-4" ><input type="text" id="name" name="client_name" /></div>
<div class="col-md-4 msg" id="nameLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Phone</div>
<div class="col-md-4" ><input type="text" id="phone" value="" /></div>
<div class="col-md-4 msg" id="phoneLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label"><input type="submit" value="Order" /></div>
<div class="col-md-4" id="totalcost"></div>
<div class="col-md-4 msg" id="submitMessage"></div>
</div>
</div>
</form>
</body>
</html>
selectedPasta[i].value will give you "0" or "50" accordingly. And they are not present in pastaPrices, hence the return value from getPastaPrice is undefined. Let me modify your jsBin and share the results.
Working JSBin here: https://jsbin.com/qokaboj/edit?html,js,console,output
Here is your working JS code:
enter code here
function getPastaPrice(){
var pastaPrice=0;
var form = document.forms["myForm"];
var selectedPasta = myForm.elements["pastatype"];
for(var i = 0; i < selectedPasta.length; i++) {
if(selectedPasta[i].checked) {
pastaPrice = pasta_prices[selectedPasta[i].id];
break;
}
}
return pastaPrice;
}
function getSaucePrice() {
var saucePrice=0;
var myForm = document.forms["myForm"];
var selectedSauce = myForm.elements["sauce"];
for(var i=0; i<selectedSauce.length; i++){
if(selectedSauce[i].selected){
saucePrice = sauce_prices[selectedSauce[i].id];
break;
}
}
return saucePrice;
}
function extrasPrice() {
var extraPrice=0;
var myForm = document.forms["myForm"];
var includeSalad = myForm.elements["salad"];
var includeSticks = myForm.elements["sticks"];
if(includeSalad.checked) {
extraPrice = 200;
}
if (includeSticks.checked) {
extraPrice += 100;
}
return extraPrice;
}
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost/100).toFixed(2));
return calculateOrder;
}
the calculateOrder function is attempting to return itself:
function calculateOrder() {
[...]
return calculateOrder;
}
This might help
You created a function called calculateOrder
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost / 100).toFixed(2));
return calculateOrder; // <--- problem here.
}
Instead of returning calculateOreder you should return ordCost.
How will this help? Well we can do some checks in your function to see that calculateOrder is...not defined! The calculateOrder that is not defined is that undefined variable I noted up there.
Go ahead a try this in your code too to see what is and is not defined in your function
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost / 100).toFixed(2));
console.log('calculateOrder: ', calculateOrder);
console.log('ordCost', ordCost)
return ordCost; //<--- the value you might be looking for
}

HTML paragraph isnt going into a straight line

I'm kinda new to programming and I cant solve this problem. The paragraphs are coming out like a stair case.
p
p
p
p
p
The p's are examples, but here is all the code I have done so far.
Keep in mind I'm not the best at css(I'm still learning)
All help would be appreciated
Please show me on how I an fix this problem, and tell me where in my code is this problem occurring.
I tried google but couldn't find anything...
var house = {}
function House() {
var msg = 'This house is painted'
var bath;
var bed;
var cook;
var Paint = document.getElementById('paint').value;
var square = document.getElementById('Square').value;
var bath = document.getElementById('bath').value;
var bed = document.getElementById('Bed').value
var cook = document.getElementById('Cook').value;
//Get paragraphs to store values
var paint = document.getElementById('isPaint');
var squareFeet = document.getElementById('sq_Feet')
var bathRoom = document.getElementById('bathroom')
var bedRoom = document.getElementById('BedRoom')
var kitchen = document.getElementById('kitchen');
if(Paint == 'Yes' || Paint == 'yes') {
house['isPainted'] = true;
paint.innerHTML = msg;
}
else if(Paint == 'No' || Paint == 'no') {
house['isPainted'] = false;
var msg = 'this house is not painted'
paint.innerHTML = msg;
}
else if(Paint == '') {
house['isPainted'] = undefined;
var msg = 'no details given';
paint.innerHTML = msg;
}
if(square != '' ) {
var squareFeetMsg = 'the house is';
squareFeet.innerHTML = squareFeetMsg + ' ' + document.getElementById('Square').value + ' square feet';
house['squareFeet'] = document.getElementById('Square').value
}else {
var squareFeetMsg = 'No Details Given';
squareFeet.innerHTML = squareFeetMsg;
}
}
body {
width: auto;
height: auto;
}
#houseDtails{
width: 350px;;
}
#container {
width: auto;
height: auto;
}
.houseDetails {
height: 0px;
float: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>House App</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="conatainer">
<div id="houseDtails">
<label for="paint">Is this house painted: </label><br>
<input type="text" id="paint" class="Detail" /><br>
<label for="Square">How many SQ feet does this have? :</label>
<input type="text" id="Square"><br>
<label for="bath">How many bathrooms does your house have</label>
<input type="text" id="bath"><br>
<label for="Bed">How many bedrooms dos your house have</label>
<input type="text" id="Bed"><br>
<label for="Cook">Does your house have a kitchen</label>
<input type="text" id="Cook"><br>
<input type="submit" name="" id="sub" class="subm" onclick="House()">
</div>
<div id="addDetailsToPage">
<p id="isPaint" class="houseDetails"></p>
<p id="sq_Feet" class="houseDetails"></p>
<p id="bathroom" class="houseDetails"></p>
<p id="Bedroom" class="houseDetails"></p>
<p id="Kitchen" class="houseDetails"></p>
</div>
</div>
<script src="House.js"></script>
</body>
The reason for the paragraphs rendering in that manner is result of float set on .houseDetails.
.houseDetails {
height: 0;
float: right;
}
This is because you have float: right; in your CSS for .houseDetails. Remove it and you should have your p aligned on the left below one another

javascript array push not working

This is my jS code. When I press the button I want to add another element with a value of 1. Right now it is resetting the the array so I never get more than one element. What do I do here?
var x = document.getElementsByTagName('button');//return button array
var age_array = [];
smoker_array = [];
relation_array = [];
age = 0;
//add button clicked
x[0].addEventListener("click", function(){
/*
var age = document.getElementsByName("age")[0].value;//pull age from box
var relation = document.getElementsByName("rel")[0].value;//pull relation
let smoker = document.querySelector('[name=smoker').checked;
//check relation
if(relation === "")
{
alert("please select a realation");
}
//check to see if age < 0
if(age < 0 || age === " ")
{
alert("age not applicable");
}
*/
age_array.push(1);
alert(age_array.length);
});
/*function submit(age, relation, smoker)
{
age_array.push(age);
alert(age_array[0]);
alert(age_array[1]);
/*
x[1].addEventListener("click", function(){
var age = JSON.stringify(entry_age);
alert(entry_age[1]);
document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);
});
}
*/
here is the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
I don't know if it is the reason, but your code won't work in strict mode.
var age_array = [];
smoker_array = [];
relation_array = [];
should be:
var age_array = [],
smoker_array = [],
relation_array = [];
or:
var age_array = [];
var smoker_array = [];
var relation_array = [];
Hey guys thanks for the help. There seems to be something wrong with the HTML. I don't know what. I got the JS working using my own HTML, and I'm not allowed to change the HTML. Anyway thanks for all y'all help.
Marking this as answered

Categories

Resources