Converter boxes, How to make it both output boxes work? - javascript

I am doing a project of a converter. When I put a number in the number box, it shows up fine in the box2. But when I try to enter a number in box2, and it won't show the answer in box1. Can anyone help me? I don't know jquery and I am a starter of html and javascript. Hopefully, someone can help me. Thanks
function NumberToSquare(num)
{
var sqrt;
sqrt = Math.sqrt(num);
return sqrt;
}
function SquareToNumber(sqrt)
{
var num;
num = Math.pow(sqrt,2);
return num;
}
<html>
<head>
<title>Program Assignment 5</title>
<script type = text/javascript src = "calculate.js"> </script>
<script type="text/javascript">
function ConvertToSqrt()
//Assumes: Number contains a number
//Results: displays the square root in box2
{
num = parseFloat(document.getElementById('box1').value);
sqrt = NumberToSquare(num);
box2.value=sqrt;
}
function ConvertToNum()
//Assumes: Square contains a number of square root
//Results: displays the number in box1
{
sqrt = parseFloat(document.getElementById('box2').value);
num = SquareToNumber(sqrt);
box1.value=num;
}
</script>
</head>
<body>
<div style="border: solid; width: 300px; background-color: #83CAFF">
<table>
<th></th> <th>Square Root Calculation</th>
<tr>
<th>Enter Number:</th><th><input type="number" id="box1" value=""></th>
<tr>
<th>SquareRoot:</th><th><input type="number" id="box2" value=""></th>
<tr>
<th></th><th><input type="button" value="Calculate" onclick="ConvertToSqrt(); ConvertToNum();">
</table>
</div>

If it helps any, here's a quick sample. It's not pretty but you can take what pieces you need and use it with your own.
<html>
<head>
<title></title>
<script>
function calc(which) {
var newVal;
if (which == "sqrt") {
newVal = parseFloat(document.getElementById("num").value);
newVal = Math.sqrt(newVal);
}
else if (which == "num") {
newVal = parseFloat(document.getElementById("sqrt").value);
newVal = Math.pow(newVal, 2);
}
document.getElementById(which).value = newVal;
}
</script>
</head>
<body>
<div style="width:400px;padding:25px;display:inline-block;line-height:150%;background-color:#83CAFF;font-weight:bold;border:solid 1px black;">
<div style="width:200px;float:left;">
<label>Number:</label>
<br />
<label>SquareRoot:</label>
</div>
<div style="width:200px;float:right;">
<input type="number" id="num"/>
<br />
<input type="number" id="sqrt"/>
</div>
<button type="button" style="width:100%;" onclick="calc('sqrt');">Calc Sqrt</button>
<button type="button" style="width:100%;" onclick="calc('num');">Calc Num</button>
</div>
</body>
</html>

Related

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

"x" is not a function at

I keep getting an error message that:
check is not a function at area question 1
and
check is not a function at HTMLInputElement.onclick
and I think this is the reason that the check() function is not running. I've looked at so many other solutions to this problem but none of them are really helpful for my issue. Any help would be greatly appreciated!
var number1;
var number2;
var response;
var calcanswer;
var score = 0;
window.onload = areaquestion1;
score.innerHTML = "SCORE: " + score;
function areaquestion1() {
var imageBlock = document.createElement("img");
imageBlock.setAttribute("id", "img");
imageBlock.setAttribute("src", "Images/2_1.png");
imageBlock.setAttribute("width", "700");
imageBlock.setAttribute("height", "400");
imageBlock.setAttribute("alt", "2_1");
document.getElementById('img').appendChild(imageBlock); // this appends it to the bottom of the page
number1 = 2
number2 = 1
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
document.getElementById("check").check();
}
function areaquestion2() {
var imageBlock = document.createElement("img");
imageBlock.setAttribute("id", "img");
imageBlock.setAttribute("src", "Images/4_2.png");
imageBlock.setAttribute("alt", "4_2");
document.body.appendChild(imageBlock); // this appends it to the bottom of the page
number1 = 4
number2 = 2
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
document.getElementById("solve").check();
}
function check() {
var statusDiv = document.getElementById("status");
response=document.getElementById("answer").value;
if(response != calcanswer)
statusDiv.innerHTML="Incorrect";
else
if (response==calcanswer)
{
statusDiv.innerHTML="Very good!";
score ++;
document.getElementById("score").textContent = score
document.getElementById("answer").value = "";
}
}
<!DOCTYPE html>
<html>
<title>Lego Area Play</title>
<head>
<link rel="stylesheet" href="CSS/gridtest.css">
<script src="JavaScript/Play.js"></script>
</head>
<body onload="areaquestion1();">
<div class="header">
<h1>LEGO AREA</h1>
<p>Calculating <b>area</b> with Emmet.</p>
<div id="scorelabel"><label>SCORE:</label></div>
<div id="score" class="score"></div>
</div>
<form>
<div class="row">
<div class="column" style="background-color:#aaa;">
<div id="question"></div>
<div id="img"></div>
<div id="status"></div>
</div>
<div class="column" style="background-color:#bbb;">
<div id ="prompt"></div>
<label>Area = </label>
<input type="text" id="answer" placeholder="Answer"/>
<label>Units<sup>2</sup></label>
</div>
<div class="column" style="background-color:#ccc;">
<input id="check" type="button" value="CHECK!" onclick="check()" />
<div class="practice"> <img src="Images/legoBlue2.png" id="practicebtn" alt="lego button for practice page" width=350px height=140px></div>
<div class="menu"> <img src="Images/menured.png" id="menubtn" alt = "lego button for menu page" width=350px height=140px></div>
</div>
</div>
</form>
</body>
</html>
As Cannicide pointed out, your second error occurs when the arequestion1() is called on load, on the line document.getElementById("check").check();
You added the check method to onclick, but that did not add a new property to the button.
Your first error is a little more complicated. This is the simplest recreation of your error I tried creating.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function f(){
console.log("f run")
}
</script>
<!-- id same as function name -->
<input id="f" type="button" value = "B1" onclick="f()" />
<!-- button inside a form -->
<form>
<input type="button" value = "B2" onclick="f()" />
</form>
<!-- button inside a form with random id -->
<form>
<input id="somethingelse" type="button" value = "B3" onclick="f()" />
</form>
<!-- button inside a form, equal id and method name -->
<form>
<input id="f" type="button" value = "B4" onclick="f()" />
</form>
</body>
</html>
There are 4 buttons, each with small difference in its environment. Notice how only the button that is inside a form and has the same id name and the onclick method name throws you an error.
To this error I unfortunately have no clue to why and how does this happen.
If someone here knows what is going on here, please explain!
cheers :)

How to increase and decrease a text value with two buttons

I'm trying to increase a text value using two buttons, one on each side of the text, which either increase the value by 10 or decrease it by 10, and the value can't go under 10km or over 90km.
Here is the app screen so you can see what I mean:
Update: I've now been given code to work with but it doesn't have the "km" value after the number so it goes 10,20,30 instead of 10km, 20km, 30km. Does anyone know how to adjust this code to do what I want?
<script language='javascript' type='text/javascript'>
$(document).ready(function(){
$("#increment").click(function(){
if($('#number').val() !="90"){
var $n = $("#number");
$n.val(Number($n.val())+10);
}
});
$("#decrement").click(function(){
if($('#number').val() !="10"){
var $n = $("#number");
$n.val(Number($n.val())-10);
}
});
});
</script>
</head>
<style>
.Radius{
font-size:14px;
font-family:"gillsans";
color: #4361AD;
text-align: center;
}
</style>
<body>
<div id="Maincontainer">
<input type="text" value="10" id="number" class="Radius" style="background-color:transparent; border:0px solid white; width:110px; margin-left:15px;"/>
<input type="button" id="increment" value="Increment"/>
<input type="button" id="decrement" value="decrement"/>
</div>
</body>
https://jsfiddle.net/deepanv29/4b7adopb/
<!DOCTYPE>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
<body>
<input type="text" value="10Km" id="number"/>
<input type="hidden" value="10" id="number1"/>
<input type="button" id="increment" value="Increment"/>
<input type="button" id="decrement" value="decrement"/>
</body>
</div>
<script language='javascript' type='text/javascript'>
$(document).ready(function(){
$("#increment").click(function(){
if($('#number1').val() !="90"){
var $n = $("#number1");
$n.val(Number($n.val())+10);
var value = $n.val();
$("#number").val(value +'Km');
}
});
$("#decrement").click(function(){
if($('#number1').val() !="10"){
var $n = $("#number1");
$n.val(Number($n.val())-10);
var value = $n.val();
$("#number").val(value +'Km');
}
});
});
</script>
</body>
</html>
updates Js fiddle demo for the above code
you just need to increment and decrement the value at button click.
int value = 10;
protected void BtnIncre_Click(Object sender, EventArgs e)
{
if (value < 90)
{
value += 10;
Session["Value"] = value;
}
}
protected void BtnDecre_Click(Object sender, EventArgs e)
{
if (value > 10)
{
value -= 10;
Session["Value"] = value;
}
}
<!DOCTYPE>
<html>
<head>
</head>
<body>
<input type="button" id="dec" value="DEC" onclick="dec();">
<input type="text" id="Number_value" value="0" readonly>
<input type="button" id="inc" value="INC" onclick="inc();">
<script language='javascript' type='text/javascript'>
function inc()
{
var val = parseInt(document.getElementById('Number_value').value);
val+=10;
if(val>90) val = 90;
document.getElementById('Number_value').value = val;
}
function dec()
{
var val = parseInt(document.getElementById('Number_value').value);
val-=10;
if(va<10) val = 10;
document.getElementById('Number_value').value = val;
}
</script>
</body>
</html>

Cant change values in text box with Javascript

I am trying to take numbers entered by a user and use them for calculating values, and then having these numbers displayed in the text boxes. When I submit the values, The text boxes to the right do not change. Any Ideas?
<!DOCTYPE html>
<html>
<head>
<title>Car Payment Calculator</title>
<style>
html, body {
margin:0;
padding:0;
}
#pagewidth {
max-width:9000em;
min-width:1000em;
}
#header {
position:relative;
height:150px;
background-color:#06F9FC;
width:100%;
display:block;
overflow:auto;
}
#maincol {
background-color: #FCC66C;
position: relative;
}
</style>
<HTA:APPLICATION ID="myCarPayment"
APPLICATIONNAME="Car Payment Calculator"
SYSMENU="yes"
BORDER="thin"
BORDERSTYLE="normal"
CAPTION="yes"
ICON=""
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="yes"
SCROLL="no"
VERSION="1.0"
WINDOWSTATE="normal"/>
<script>
window.resizeTo(300,300);
function calculate() {
var years= document.forms.myForm.years.value;
var monthly= amount/(years*12);
var number= monthly/amount;
var form = document.forms.myForm;
var loanAmount = form.loanAmount.value;
var downPayment = '0';
var anualInterestRate = form.interestRate.value;
var years = form.years.value;
var monthRate = anualInterestRate/12;
var numberOfPayments = years * 12;
var Principal=loanAmount-downPayement;
var valueNumber = document.getElementById("numPay");
var vlaueMonthly = document.getElementById("monthlyPay");
valueNumber.value = numberOfPayments;
valueMonthly.value = monthly;
}
</script>
</head>
<body>
<div id="header">
<pre>
<p>This application will help you calculate car payments.<br/>
Just enter the information and hit Calculate!</p>
</pre>
</div>
<div id="maincol">
<pre>
<form name="myForm" action="" onsubmit="calculate()">
<table>
<tr>
<td>Loan Amount:</td><td> <input type="number" name="loanAmount"></td>
</tr>
<tr>
<td>Interest Rate:</td><td> <input type="number" name="interestRate"></td><td>Number of Payments:</td><td><input type="text" name="numberPayments" id="numPay" value="0"></td>
</tr>
<tr>
<td>Number of Years:</td><td> <input type="number" name="years"></td><td>Monthly Payment:</td><td><input type="text" name="monthlyPayments" id="monthlyPay" value="0"></td>
</tr>
<tr>
<td><input type="submit" value="Calculate"></td>
</tr>
</table>
</form>
</pre>
</div>
</body>
</html>
You are getting an error in your callback function calculate():
Uncaught ReferenceError: amount is not defined
You're using amount but you've not defined/declared it.
I'm not sure what the value of amount should be.
Also get the value from input and convert it into number by using parsetInt(), you need convert them into number before calculation.
var years = parseInt(document.forms.myForm.years.value, 10);
var loanAmount = parseInt(form.loanAmount.value, 10);
var valueNumber = parseInt(document.getElementById("numPay"), 10);
var vlaueMonthly = parseInt(document.getElementById("monthlyPay"), 10);

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Categories

Resources