My function in html isn't working properly - javascript

I made a function to calculate average and tried to use this function in each section. But the calculation isn't working properly. If you see the code below, the handleCalculateAverageButtonClick('Question1') function works in first section (section class = "Question1") but the handleCalculateAverageButtonClick('Question2') function's calculation is wrong in the second section (second class="Question2"). Is there something to modify in my code?
html code
<section class = "Question1">
how many times do you want to buy on scale?
<input type = "number" style = "height : 20px ; width: 50px; " class = "scale-count" />
<button type = "button" onclick = "handleNextButtonClick('Question1')" style = "padding
: 4px 19px;">
Next
</button>
<div class = "form-output"> </div>
<br>
<button class = "button button1" onclick =
"handleCalculateAverageButtonClick('Question1')">
CalculateAverage
</button> :
<span class= "average1"></span>
</section>
<section class = "Question2">
How many times do you want to sell on scale?
<input type = "number" style ="height : 20px; width: 50px;" class = "scale-count" />
<button type = "button" onclick = "handleNextButtonClick('Question2')" style =
"padding:4px 19px;">
Next
</button>
<div class = "form-output"></div>
<br>
<button class = "button button1" onclick =
"handleCalculateAverageButtonClick('Question2')">
CalculateAverage
</button> :
<span class = "average1"></span>
</section>
javascript code
function getNumberOfScales(){
const temp = parseInt(document.querySelector("." + parent + " .scale-count").value);
const numberOfScales = isNaN(temp) || temp<0 ? 0 : temp;
return numberOfScales;
}
function rowGenerator(index){
return `
<div class = "row" data-index = "${index}">
&nbsp &nbsp Price ${index} : &nbsp <input class = "price" style = "height : 30px ; width:
50px;"
data-index = "${index}" type = "number" /> &nbsp Count : &nbsp
<input class = "count" style = "height : 30px ; width: 50px;" data-index = "${index}" type
= "number" />
</div> `;
}
function handleNextButtonClick(parent){
const numberOfScales = getNumberOfScales(parent);
const formOutput = document.querySelector("."+parent+" .form-output");
let stringBuffer = " ";
for (let index=1; index<= numberOfScales; index++){
stringBuffer += rowGenerator(index);
}
formOutput.innerHTML = stringBuffer;
}
function getAverage(parent){
let sum = 0 ;
let sum_count = 0;
const numberOfScales = getNumberOfScales(parent);
for (let index = 1; index <= numberOfScales; index++){
const row_price = document.querySelector(`input.price[data-index = '${index}']`).value ;
const row_count = document.querySelector(`input.count[data-index = '${index}']`).value ;
sum += row_price * row_count;
sum_count += parseInt(row_count);
}
console.table({
sum,
sum_count
})
if (sum_count ==0 ){
return 0;
} else{
return sum/sum_count ;
}
}
function handleCalculateAverageButtonClick(parent) {
const average = getAverage(parent);
const avg1 = document.querySelector("." + parent +" .average1");
avg1.innerHTML = average;
}

Related

Display slider when you hover over array elements and give value to the array elements

I have done the part where you have to generate the array elements when you enter them from textbox, what I struggle with now is to display a slider on hover over each array element and give the array element a value, also what I struggle with is to delete each generated array element individually, my delete function deletes the entire array on click not just the single element I click.
Here is how it should look like:
enter image description here
Here is my code so far:
let names = [];
let nameInput = document.getElementById("name");
let messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
clearAndShow();
}
function remove()
{
var element = document.getElementById("display");
element.parentNode.removeChild(element);
}
function clearAndShow () {
let printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.style.borderStyle = "solid"
_span.style.borderColor = "blue"
_span.style.width = '50px'
_span.style.marginLeft = "5px"
_span.appendChild(document.createTextNode(element))
messageBox.appendChild(_span)
printd +="''" + element + "''" + "," + " ";
document.getElementById("labelprint").innerHTML=(printd)
}
})
}
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
<div class="container">
<form>
<h1>Enter Search</h1>
<input id="name" type="text" />
<input type="button" value="Search" onclick="insert()" />
</form>
<br/>
<div onclick="remove(this)" id="display"></div>
<br/>
<label >You have Selected: </label>
<h3 id="labelprint"></h3>
</div>
I am not being rude I just got confused on how you stated your message but what I think you are saying is to do this:
var names = [];
var nameInput = document.getElementById("name");
var messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
// add value to array val: names[names.length - 1] = PutValueHere
clearAndShow();
}
function remove(this){
document.getElementById("display").parentNode.firstChild.remove(); // If you want it to remove the last child with the id 'display' then do .parentNode.lastChild.remove()
//if you are trying to remove the last val in the array do this: names.splice(names.length-1,1) for the first do this names.splice(0,1)
}
function clearAndShow () {
var printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.id = '_spanId'
$('_spanId').css('border-style',solid');
$('_spanId').css('border-color',blue');
$('_spanId').css('width',50+'px');
$('_spanId').css('margin-left',5+'px');
_span[0].appendChild(document.createTextNode(element))
messageBox[0].appendChild(_span)
printd += "''" + element + "'', ";
document.getElementById("labelprint").innerHTML = printd
}
})
}
I have tried to implement something that i hope it's close to what are you looking for:
HTML:
<div class="container">
<form>
<h1>Add new slider</h1>
<input id="sliderName" type="text" />
<input type="button" value="Add" onclick="insertSlider()" />
</form>
<div id="display"></div>
</div>
CSS:
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
JS:
let messageBox = document.getElementById("display");
function deleteFn(id) {
const element = document.getElementById(id)
if(element) element.outerHTML="";
}
function onChangeSlideId(id){
const elementSlide = document.getElementById('slider-'+id+'')
if(elementSlide){
const value = elementSlide.value
const elementSlideText = document.getElementById('slider-value-'+id+'')
elementSlideText.innerText = '('+value+')'
}
}
function insertSlider(){
const name = document.getElementById("sliderName")
const nameValue = name.value
const newLabel = document.createElement('label')
newLabel.setAttribute('for',nameValue)
newLabel.innerText = nameValue
const newSlider = document.createElement('input')
newSlider.setAttribute('id','slider-'+nameValue+'')
newSlider.setAttribute('type','range')
newSlider.setAttribute('name',nameValue)
newSlider.setAttribute('onchange','onChangeSlideId("'+nameValue+'")')
const sliderValue = document.createElement('span')
sliderValue.setAttribute('id','slider-value-'+nameValue+'')
sliderValue.innerText = '('+newSlider.value+')'
const newContainer = document.createElement('div')
newContainer.setAttribute('id',nameValue)
newContainer.setAttribute('style','display: grid')
newContainer.appendChild(newSlider)
newContainer.appendChild(newLabel)
newContainer.appendChild(sliderValue)
const newDeleteButton = document.createElement('input')
newDeleteButton.setAttribute('type', 'button')
newDeleteButton.setAttribute('value', 'Delete ' + nameValue + '')
newDeleteButton.setAttribute('onclick', 'deleteFn("'+nameValue+'")')
newContainer.appendChild(newDeleteButton)
messageBox.appendChild(newContainer)
}
You can try it by yourself in this codepen

Manipulation of div elements with javascript

Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.

Having trouble displaying total cost

I am struggling to calculate the totalPrice and finalPrice, I've been working on this for hours. I tried everything, am I supposed to put the if and else statements in the script? Tried everything, doesn't work, my clear button doesn't clear either. Thanks for your help!!!
<html>
<head>
<meta charset = "UTF-8">
<title> World Travel </title>
<style>
body {background-color: black; font-family: optima;
color: white; text-align: left}
p { font-size: 20px}
button {font-size: 20px; background-color: white}
input { font-size: 20px}
</style>
</head>
<body>
<script>
var hotelNights= 0;
var travelPrice = 0;
var totalPrice = 0;
var finalPrice = 0;
</script>
<h1> World Travel </h1>
<h2> Price Processing </h2>
<p> Select Destination:
<input type = "radio" id = "a" name = "destination" size = "3"
onclick = /> Europe
<input type= "radio" id = "b" name= "destination" size = "3"
onclick = "destination == 'a';" /> Africa
</p>
<p> Select Air Travel Option:
<input type = "radio" id = "o" name = "airTravel" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 500; }
else {
totalPrice += 700; }
" /> One Way
<input type= "radio" id = "x" name = "airTravel" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 900; }
else {
totalPrice += 1300; }
" /> Round Trip
</p>
<p> Enter number of Hotel nights:
<input type = "text" id = "hotelNights" value = ""
onchange = "
if (destination == "e") {
totalPrice += 300*document.getElementaryById("hotelNights").value; }
else {
totalPrice += 200*document.getElementaryById("hotelNights").value; } " />
</p>
<p> Select Tour type:
<input type = "radio" id = "g" name = "tourPrice" size = "3"
onclick = "
if (desination == "e") {
totalPrice += 1500; }
else {
totalPrice + = 1300; } "/> Grand Package
<input type = "radio" id = "z" name = "tourPrice" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 800; }
else {
totalPrice += 500; } " /> Basic Package
</p>
<p>
<button onclick="
finalPrice= (totalPrice*1.15);
totalPriceTextBox.value = '$' + totalPrice.toFixed(2);
finalPriceTextBox.value = '$' + finalPrice.toFixed(2);
"> Process </button>
</p>
<p> Total Price: $
<input type = "text" id = "totalPriceTextBox" value = "" readonly />
</p>
<p> Final Price (includes 15% surcharge): $
<input type = "text" id = "finalPriceTextBox" value = "" readonly />
</p>
<p>
<button onclick= "
a.checked = false;
hotelNights = '';
o.checked = false;
g.checked = false;
totalPriceTextBox.value = '';
finalPriceTextBox.value = '';
id_of_radio_button.checked = false;
id_of_text_box = '';
"> Clear </button>
</p>
<body>
</html>
......................................................................................................................................................................................................................................................................................................................................................................................................
You can't use double quotes in an inline onclick handler:
onclick = "
if (destination == "e") { // Can't use double quotes here because you're already inside a set of double quotes!
totalPrice += 900; }
else {
totalPrice += 1300; }
" />
You also need to declare and initialize destination.
Also, this onclick looks wrong:
<input type = "radio" id = "a" name = "destination" size = "3"
onclick = /> Europe

Unable to display text box results in div

I want to display all the resulting expressions under the Result and Entered button every time I hit "=". But I am stuck trying to figure it out. This is what I have so far. Any help would be much appreciated. Thank you.
<!DOCTYPE html>
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = ["document.getElementById('op1').value", "document.getElementById('operator').value", "document.getElementById('op2').value",
"=","document.getElementById('result').value"];
dispArr.toString();
document.getElementbyId("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>
The values for dispArr are in quotes so they're treated as strings. Remove the quotes, then you are using document.getElementbyId instead of document.getElementById on line 39 (under dispArr.toString();)
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = [document.getElementById('op1').value, document.getElementById('operator').value, document.getElementById('op2').value,
"=",document.getElementById('result').value];
dispArr.toString();
document.getElementById("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>

Adding input fields to a HTML form

I want to dynamically add form input fields to a form using the javascript below by clicking on the add button:
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("Name", "a_level[ + i ][0]");
r.appendChild(y);
z.setAttribute("Name", "a_level[ + i ][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class = "dash-form" method = "POST" action = "/" >
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[+i][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[+i][1]" value = "" placeholder = "Course"/>
</div>
<div class = "dash-submit">
<input class = "dash-submit-button" type = "submit" value = "Submit"/>
</div>
</form>
<div class = "dash-add">
<button class = "dash-add-button" onclick = "addfieldFunction()">ADD</button>
</div>
The function returns an i instead of incrementing and returning an integer as shown below:
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[0][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[0][1]" value = "" placeholder = "Course"/>
</div>
Concatenate variable i using +(concatenation operator) operator
The concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("name", "a_level[ " + i + " ][0]"); //Keep attribute in lower case
r.appendChild(y);
z.setAttribute("name", "a_level[ " + i + "][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class="dash-form" method="POST" action="/">
<div id="form-div">
<input class="dash-input" type="text" name="a_level[+i][0]" value="" placeholder="University" />
<input class="dash-input" type="text" name="a_level[+i][1]" value="" placeholder="Course" />
</div>
<div class="dash-submit">
<input class="dash-submit-button" type="submit" value="Submit" />
</div>
</form>
<div class="dash-add">
<button class="dash-add-button" onclick="addfieldFunction()">ADD</button>
</div>
You need to concatenate it like this:
y.setAttribute("name", "a_level[" + i +"][0]");
As Rayon pointed out: keep attributes in lower case although the HTML5 standard does not require lower case attribute names (see here). W3C recommends it though and XHTML validation would fail using uppercase letters.

Categories

Resources