Stuck with javascript (beginner) - javascript

I have just started learning javascript and i am stuck with my first lab. I have the HTML part working but none of the javascript is working. At first I thought it did not link the javascript code to the HTML code correctly but now i think there is issues with the onload and oninput part. But have no idea why. If someone can help would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
Your Birthday:<input type="date" id="dod"/>
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>
window.onload = function() {
var para = document.getElementById("heading");
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};

I have made a couple of edits:
Missing id on the heading element
typo on the id="dob" you had id="dod"
window.onload = function() {
/******* EDIT 1 ********/
// the heading element has no ID, so you need to add one, or use `querySelector` instead.
//var para = document.getElementById("heading");
var para = document.querySelector("heading");
/***********************/
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
<!-- EDIT 2 -->
<!-- You had a typo on the id of your input 'dod' -> 'dob' -->
<!-- Your Birthday:<input type="date" id="dod"/> -->
Your Birthday:<input type="date" id="dob"/>
<!-- End EDIT -->
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>

Related

Display answer of 'Add and Subtract' buttons using javascript

So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>
//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>

broken JavaScript program with no errors [duplicate]

I am in a beginning JavaScript class and very new to programming. I am attempting to make a program that converts Celsius to Fahrenheit or Fahrenheit to Celsius depending on which radio button is clicked.
I feel like I have most of working, although it may not be the most elegant code. The one thing I can't figure out is is why the converted value won't display using $("degrees_computed").innerHTML.
What am I missing? Why won't the converted value display?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var toFahrenheit = function() {
if ($("to_fahrenheit").checked) {
$("degree_label_1").innerHTML = "Enter C degrees:";
$("degree_label_2").innerHTML = "Degrees Fahrenheit:";
}
clearTextBoxes();
}
var toCelsius = function() {
if ($("to_celsius").checked) {
$("degree_label_1").innerHTML = "Enter F degrees:";
$("degree_label_2").innerHTML = "Degrees Celsius:";
}
clearTextBoxes();
}
var convertTemp = function() {
var fahrenheit;
var celsius;
if ($("to_fahrenheit").checked) {
celsius = $("degrees_entered").value;
celsius = (celsius * (9 / 5)) + 32;
celsius = parseFloat(celsius);
celsius = celsius.toFixed(0);
$("degrees_computed").innerHTML = celsius;
}
if ($("to_celsius").checked) {
fahrenheit = $("degrees_entered").value;
fahrenheit = parseFloat(fahrenheit);
fahrenheit = (fahrenheit - 32) * (5 / 9);
fahrenheit = fahrenheit.toFixed(0);
$("degrees_computed").disabled = false;
$("degrees_computed").innerHTML = fahrenheit;
}
}
var clearTextBoxes = function() {
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function() {
$("convert").onclick = convertTemp;
$("to_celsius").onclick = toCelsius;
$("to_fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Temperature Converter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main>
<h1>Temperature Converter</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered"><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
<script src="convert_temp.js"></script>
</body>
</html>
Your output fields are <input> elements. To fill them in you must assign to .value, not .innerHTML.
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var toFahrenheit = function() {
if ($("to_fahrenheit").checked) {
$("degree_label_1").innerHTML = "Enter C degrees:";
$("degree_label_2").innerHTML = "Degrees Fahrenheit:";
}
clearTextBoxes();
}
var toCelsius = function() {
if ($("to_celsius").checked) {
$("degree_label_1").innerHTML = "Enter F degrees:";
$("degree_label_2").innerHTML = "Degrees Celsius:";
}
clearTextBoxes();
}
var convertTemp = function() {
var fahrenheit;
var celsius;
if ($("to_fahrenheit").checked) {
celsius = $("degrees_entered").value;
celsius = (celsius * (9 / 5)) + 32;
celsius = parseFloat(celsius);
celsius = celsius.toFixed(0);
$("degrees_computed").value = celsius;
}
if ($("to_celsius").checked) {
fahrenheit = $("degrees_entered").value;
fahrenheit = parseFloat(fahrenheit);
fahrenheit = (fahrenheit - 32) * (5 / 9);
fahrenheit = fahrenheit.toFixed(0);
$("degrees_computed").disabled = false;
$("degrees_computed").value = fahrenheit;
}
}
var clearTextBoxes = function() {
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function() {
$("convert").onclick = convertTemp;
$("to_celsius").onclick = toCelsius;
$("to_fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Temperature Converter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main>
<h1>Temperature Converter</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered"><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
<script src="convert_temp.js"></script>
</body>
</html>
You should not use innerHTML for <input> tags, instead use value
Since you are using jquery you could also use $("degrees_computed").val(myResultVariable)
Could be working with innerHTML if your result html tag was a <a> <div> <span> <label> or any other tag than elements like <input> or <img>
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
degrees_computed is input so you basically replace
$("degrees_computed").innerHTML =
with
$("degrees_computed").value =

how to apply discount

I am building a ticket purchase system to get better in my javascript. I need help with some of my code. I can get the total of everything I want, but I am unable to get my discount function to work.
The total is calculated as (Show price * number of tickets) + (price of the delivery method)
when: the number of tickets > 6 the discount should be 10 per cent of the total.
when: the number of tickets > 10 the discount should be 15 per cent of the total.
the discount should be displayed separately to the total.
Dont mind some of the code that are comments as i used that as refrences.
This is the code:
java script:
//constants
const name = document.getElementById("fname");
const noofaddress = document.getElementById("noofaddress");
const shows = document.getElementById("shows");
const delivery = document.getElementById("delivery");
const displaytotal = document.getElementById("displaytotal");
const seatprice = document.getElementById("seatprice");
const order = document.getElementById("book");
const showselect = document.querySelector("#shows");
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//amount
var showprices = new Array();
showprices["79"]=79;
showprices["85"]=85;
showprices["67"]=67;
showprices["83"]=83;
function getshowprice() {
const display = document.getElementById("display");
var showprice = 0;
var form = document.forms["bookform"];
var selectedshow = form.elements["shows"]
showprice = showprices[selectedshow.value];
return showprice;
}
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//functions
//function calculateshowcost() {
//showcost = Number(this.value);
//document.getElementById('display').innerHTML = (`£${bookform.shows[bookform.shows.selectedIndex].value}`);
//}
//delivery funtion
//function getDeliveryValue() {
// document.getElementById('displaydelivery').innerHTML = (`£${bookform.delivery[bookform.delivery.selectedIndex].value}`);
//}
var deliveryprices = new Array();
deliveryprices["0"]=0;
deliveryprices["1.50"]=1.50;
deliveryprices["3.99"]=3.99;
function getdeliveryprice() {
const displaydelivery = document.getElementById("displaydelivery");
var deliveryprice = 0;
var form = document.forms["bookform"];
var selecteddelivery = form.elements["delivery"]
deliveryprice = deliveryprices[selecteddelivery.value];
return deliveryprice;
}
function gettotal() {
const displaytotal = document.getElementById("displaytotal");
const seats = document.getElementById("seats");
const noofseats = document.querySelector("#seats");
var showtotal = getshowprice()
var showdeliverytotal = getdeliveryprice()
var seatstotal = noofseats.value;
displaytotal.innerText = (`Total: £${(showtotal * seatstotal) + (showdeliverytotal)}`);
}
function getdiscount(products, showtotal, seatstotal) {
const discount = document.getElementById('discount');
var x = 6
if (seatstotal > x) {
(seatstotal > 10)
DiscountPrice = showtotal - (showtotal * .10)
}
else if
{
DiscountPrice = showtotal - (showtotal * .10)
}
return showtotal > y;
discount.innerText = (`discount: £${(DiscountPrice)}`);
// total
//function totalprice(event) {
//event.preventDefault()
//showprice = Number(showselect.value);
//totalnumberoftickets = Number(noofseats.value);
//totalcost = (showprice * totalnumberoftickets) + deliverycost;
//displaytotal.innerText = totalTickets;
//totalPriceResult.innerText = totalPrice;
//console.log("thank you for your order")
//}
html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="theatre tickets page for assignment">
<link rel="stylesheet" href="theatretickets.css">
<title>Theatre Tickets</title>
</head>
<body class="background">
<script src="theatretickets.js"></script>
<img class="logoimage" src="" alt="logo">
<h1 class="title">Theatre Tickets</h1>
<!--navigation -->
<nav>
<ul class="a">
<li class="hp">Fruit Machine</li>
<li class="hp">Theatre Tickets</li>
</ul><br><br>
</nav>
<!--forms-->
<!--name-->
<form name="bookform" id="bookform" class="fullform" method="post">
<h2>Name</h2>
<label for="fname">Full Name</label><br>
<input type="text" id="fname" name="fname" required=""><br>
<!--address-->
<h2>Address</h2>
<label for="noofaddress">Full Address</label><br>
<input type="text" id="noofaddress" name="noofaddress" required=""><br>
<!--shows-->
<h2>Currently Available Shows</h2>
<select name="shows" id="shows" onchange="getshowprice()">
<option value="79" selected class="Phantom" id="Phantom">Phantom Of The Opera</option>
<option value="85" class="hamilton" id="hamilton">Hamilton</option>
<option value="67" class="lionking" id="lionking">Lion King</option>
<option value="83" class="misssaigon" id="misssaigon">Miss Saigon</option>
</select><br>
<label id="display"></label>
<!--delivery-->
<h2>Method Of Delivery</h2>
<select id="delivery" name="delivery" onchange="getdeliveryprice()">
<option id="eticket" value="0" selected>E-Ticket</option>
<option id="boxoffice" value="1.50">Collect from Box Office</option>
<option id="posted" value="3.99">Posted</option>
</select><br>
<!--display the delivery cost label-->
<label id="displaydelivery"></label>
<!--seats-->
<h2>Number Of Seats</h2>
<input type="number" id="seats" name="seats" min="1" required=""
placeholder="Number of Seats"><br>
<label id="seatprice"></label><br><br>
<!--book button-->
<button type="button" name="book" id="book" onclick="gettotal()">Book</button><br><br>
<div id= "displaytotal"></div>
<div id="discount"></div>
<div id="finalcost"></div>
</form>
</body>
When no. of ticket is greater than 10, you are still applying 10%, so replace it with 15%, and I think you should first check condition for 10 and then condition for 6 in your if-else, see the new edited code. I don't know what is y here so can't comment on that.
//constants
const name = document.getElementById("fname");
const noofaddress = document.getElementById("noofaddress");
const shows = document.getElementById("shows");
const delivery = document.getElementById("delivery");
const displaytotal = document.getElementById("displaytotal");
const seatprice = document.getElementById("seatprice");
const order = document.getElementById("book");
const showselect = document.querySelector("#shows");
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//amount
var showprices = new Array();
showprices["79"]=79;
showprices["85"]=85;
showprices["67"]=67;
showprices["83"]=83;
function getshowprice() {
const display = document.getElementById("display");
var showprice = 0;
var form = document.forms["bookform"];
var selectedshow = form.elements["shows"]
showprice = showprices[selectedshow.value];
return showprice;
}
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//functions
//function calculateshowcost() {
//showcost = Number(this.value);
//document.getElementById('display').innerHTML = (`£${bookform.shows[bookform.shows.selectedIndex].value}`);
//}
//delivery funtion
//function getDeliveryValue() {
// document.getElementById('displaydelivery').innerHTML = (`£${bookform.delivery[bookform.delivery.selectedIndex].value}`);
//}
var deliveryprices = new Array();
deliveryprices["0"]=0;
deliveryprices["1.50"]=1.50;
deliveryprices["3.99"]=3.99;
function getdeliveryprice() {
const displaydelivery = document.getElementById("displaydelivery");
var deliveryprice = 0;
var form = document.forms["bookform"];
var selecteddelivery = form.elements["delivery"]
deliveryprice = deliveryprices[selecteddelivery.value];
return deliveryprice;
}
function gettotal() {
const displaytotal = document.getElementById("displaytotal");
const seats = document.getElementById("seats");
const noofseats = document.querySelector("#seats");
var showtotal = getshowprice()
var showdeliverytotal = getdeliveryprice()
var seatstotal = noofseats.value;
displaytotal.innerText = (`Total: £${(showtotal * seatstotal) + (showdeliverytotal)}`);
}
function getdiscount(products, showtotal, seatstotal) {
const discount = document.getElementById('discount');
var x = 10;
var DiscountPrice = 0;
if (seatstotal > x) {
DiscountPrice = showtotal - (showtotal * .15)
}
else if
(seatstotal > 6)
DiscountPrice = showtotal - (showtotal * .10)
}
return showtotal > y;
discount.innerText = (`discount: £${(DiscountPrice)}`);
// total
//function totalprice(event) {
//event.preventDefault()
//showprice = Number(showselect.value);
//totalnumberoftickets = Number(noofseats.value);
//totalcost = (showprice * totalnumberoftickets) + deliverycost;
//displaytotal.innerText = totalTickets;
//totalPriceResult.innerText = totalPrice;
//console.log("thank you for your order")
//}

Beginning JavaScript - displaying temperature value in Inner HTML

I am in a beginning JavaScript class and very new to programming. I am attempting to make a program that converts Celsius to Fahrenheit or Fahrenheit to Celsius depending on which radio button is clicked.
I feel like I have most of working, although it may not be the most elegant code. The one thing I can't figure out is is why the converted value won't display using $("degrees_computed").innerHTML.
What am I missing? Why won't the converted value display?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var toFahrenheit = function() {
if ($("to_fahrenheit").checked) {
$("degree_label_1").innerHTML = "Enter C degrees:";
$("degree_label_2").innerHTML = "Degrees Fahrenheit:";
}
clearTextBoxes();
}
var toCelsius = function() {
if ($("to_celsius").checked) {
$("degree_label_1").innerHTML = "Enter F degrees:";
$("degree_label_2").innerHTML = "Degrees Celsius:";
}
clearTextBoxes();
}
var convertTemp = function() {
var fahrenheit;
var celsius;
if ($("to_fahrenheit").checked) {
celsius = $("degrees_entered").value;
celsius = (celsius * (9 / 5)) + 32;
celsius = parseFloat(celsius);
celsius = celsius.toFixed(0);
$("degrees_computed").innerHTML = celsius;
}
if ($("to_celsius").checked) {
fahrenheit = $("degrees_entered").value;
fahrenheit = parseFloat(fahrenheit);
fahrenheit = (fahrenheit - 32) * (5 / 9);
fahrenheit = fahrenheit.toFixed(0);
$("degrees_computed").disabled = false;
$("degrees_computed").innerHTML = fahrenheit;
}
}
var clearTextBoxes = function() {
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function() {
$("convert").onclick = convertTemp;
$("to_celsius").onclick = toCelsius;
$("to_fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Temperature Converter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main>
<h1>Temperature Converter</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered"><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
<script src="convert_temp.js"></script>
</body>
</html>
Your output fields are <input> elements. To fill them in you must assign to .value, not .innerHTML.
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var toFahrenheit = function() {
if ($("to_fahrenheit").checked) {
$("degree_label_1").innerHTML = "Enter C degrees:";
$("degree_label_2").innerHTML = "Degrees Fahrenheit:";
}
clearTextBoxes();
}
var toCelsius = function() {
if ($("to_celsius").checked) {
$("degree_label_1").innerHTML = "Enter F degrees:";
$("degree_label_2").innerHTML = "Degrees Celsius:";
}
clearTextBoxes();
}
var convertTemp = function() {
var fahrenheit;
var celsius;
if ($("to_fahrenheit").checked) {
celsius = $("degrees_entered").value;
celsius = (celsius * (9 / 5)) + 32;
celsius = parseFloat(celsius);
celsius = celsius.toFixed(0);
$("degrees_computed").value = celsius;
}
if ($("to_celsius").checked) {
fahrenheit = $("degrees_entered").value;
fahrenheit = parseFloat(fahrenheit);
fahrenheit = (fahrenheit - 32) * (5 / 9);
fahrenheit = fahrenheit.toFixed(0);
$("degrees_computed").disabled = false;
$("degrees_computed").value = fahrenheit;
}
}
var clearTextBoxes = function() {
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function() {
$("convert").onclick = convertTemp;
$("to_celsius").onclick = toCelsius;
$("to_fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Temperature Converter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main>
<h1>Temperature Converter</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered"><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
<script src="convert_temp.js"></script>
</body>
</html>
You should not use innerHTML for <input> tags, instead use value
Since you are using jquery you could also use $("degrees_computed").val(myResultVariable)
Could be working with innerHTML if your result html tag was a <a> <div> <span> <label> or any other tag than elements like <input> or <img>
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
degrees_computed is input so you basically replace
$("degrees_computed").innerHTML =
with
$("degrees_computed").value =

How to replace an appendChild instead of it adding to the previous appendChild?

I created a simple simple javascript program where when I click two buttons that I generate random numbers and the third button allows me to sum the two numbers up and then I can reset.
Codepen with update
<html lang="en">
<head>
<title>createTextNode example</title>
</head>
<body>
<button onclick="addTextNode1('Hi!');">N. 1</button>
<button onclick="addTextNode('NO! ');">N. 2</button>
<button onclick="test2('NO!.. ');">A! </button>
<button onclick="myFunction3()">Reset page</button>
<hr />
<p id="p2">1: </p>
<p id="p1">2: </p>
<p id="p3">T: </p>
</body>
</html>
function addTextNode(simple1) {
text1 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text1+" "),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
function addTextNode1(simple2) {
text2 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text2+" "),
p2 = document.getElementById("p2");
p2.appendChild(newtext);
}
function myFunction3() {
window.location.reload(true);
}
function test2() {
text5 = text1 + text2;
var newtext5 = document.createTextNode(text5),
p3 = document.getElementById("p3");
p3.appendChild(newtext5);
}
My question is how would I be able to replace the number that was newly displayed by the button by the appendChild method, so that when I click the button again the previous number gets replaced.
Thanks! Much appreciate!
Here an example for the second number.Same for the other:
function addTextNode(simple1) {
text1 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text1+" "),
p1 = document.getElementById("p1");
var p1Txt=p1.innerHTML;
var a=p1Txt.length;
if(a>=3){
p1.innerHTML='2: ';
p1.appendChild(newtext);
}else{
p1.appendChild(newtext);
}
Great to hear that you are programming!
Nice post about onclick attribute attaching events
If you need some functionality more than once,wrap this in a function.(random integer).It makes code cleaner and you dont need to repeat yourself.
Check this out.I bet this example is far from perfect but still give some insights
// You can use some library like "Lodash" to use such functions.
// returns random integer in span <min:max>
function randomInteger(min = 1, max = 100){
// in case that there are wrong values
if(min >= max){throw new Error(`Hey i cant get random integer in range min:${min} to max:${max}`)}
return Math.round((Math.random() * (max-min))+min)
}
// buttons
var number1GeneratorButton = document.getElementById('number1-generator'),
number2GeneratorButton = document.getElementById('number2-generator'),
calculateSumButton = document.getElementById('sum-button'),
resetPageButton = document.getElementById('reset-page');
// outputs
var number1Output = document.getElementById('number1'),
number2Output = document.getElementById('number2'),
sumOutput = document.getElementById('sum');
// add event listeners to the buttons
number1GeneratorButton.addEventListener('click', function(){
number1Output.innerHTML = randomInteger();
})
number2GeneratorButton.addEventListener('click', function(){
number2Output.innerHTML = randomInteger();
})
calculateSumButton.addEventListener('click', function(){
var sum = parseInt(number1Output.innerHTML) + parseInt(number2Output.innerHTML);
sumOutput.innerHTML = sum;
})
resetPageButton.addEventListener('click', reloadWindow)
function reloadWindow() {
window.location.reload(true);
}
// function addTextNode2(simple3) {
// text3 = text2 + text1
// var newtext1 = document.createTextNode(text3),
// p3 = document.getElementById("p3");
// p3.appendChild(newtext1);
// }
// function addTextNode4() {
// if (text1 > text2){
// text3 = text1 - text2;
// var newtext4 = document.createTextNode(text3),
// p3 = document.getElementById("p3");}
// else if(text2 > text1){
// text3 = text2 - text1;");}
// var newtext4 = document.createTextNode(text3),
// p3 = document.getElementById("p3
// p3.appendChild(newtext4);
// }
// function test(sampleplace1){
// if(text1 > text2){
// q = text1 - text2;
// var storm = document.createTextNode(q).value,
// p1 = document.getElementById("p1");}
// else if(text2 > text1){
// z = text2 - text1;
// var storm = document.createTextNode(z).value,
// p1 = document.getElementById("p1");
// }
// p1.appendChild(storm);
// }
<html lang="en">
<head>
<title>createTextNode example</title>
</head>
<body>
<button id="number1-generator">Number1Generator</button>
<button id="number2-generator">Number2Generator</button>
<button id="sum-button">CalculateSum</button>
<button id="reset-page">Reset page</button>
<hr />
<p>Number1: <span class="numbers" id="number1"></span></p>
<p>Number2: <span class="numbers" id="number2"></span></p>
<p>Sum: <span id="sum"></span></p>
</body>
</html>

Categories