JavaScript: Combining functions and scripts and buttons - javascript

I am going through the SAMS Learn JavaScript in 24 hours book. The end of lesson three has an extra exercise to combine a Celsius to Fahrenheit from Lesson 2, with functions and buttons from Lesson 3. I was able to successfully complete the Try It exercises in Lessons 2 and 3...
LESSON 2
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp = 100; // temperature in Celsius
var hTemp = ((cTemp * 9) /5 ) + 32;
document.write("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
LESSON 3
<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
<script>
function buttonReport(buttonId, buttonName, buttonValue) {
var userMessage1 = "Button id: " + buttonId + "\n";
var userMessage2 = "Button name: " + buttonName + "\n";
var userMessage3 = "Button value: " + buttonValue;
alert(userMessage1 + userMessage2 + userMessage3);
}
</script>
But I am stuck combining the two.
EXERCISE TO COMBINE THE TWO:
Write a function to take a temperature value in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Lesson 2.
Test your function in an HTML page having three buttons that, when clicked, pass values of 10, 20, and 30 degrees Celsius, respectively, to the function.
HERE'S WHAT I HAVE...(minus the headers, titles and HTML tags)
function temp(10, 20, 30) {
var hTemp1 = ((temp * 9) /5 ) + 32;
var hTemp2 = ((temp * 9) /5 ) + 32;
var hTemp3 = ((temp * 9) /5 ) + 32;
alert(hTemp1, hTemp2, hTemp3);
}
</script>
</head>
<body>
<input type="button" value="10 X Celsius" onclick = hTemp1>
<input type="button" value="20 X Celsius" onclick = hTemp2>
<input type="button" value="30 X Celsius" onclick = hTemp3>
Can you please help me?

There's definitely better ways to do this. But here's a solution for the purpose of this lesson. I tried not to change too much of your code. Check out the snippet below.
function toF(cTmp) {
return cTmp * 9 / 5 + 32
}
function alertF(tmp) {
alert(toF(tmp))
}
<input type="button" value="10" onclick="alertF(10)">
<input type="button" value="20" onclick="alertF(20)">
<input type="button" value="30" onclick="alertF(30)">

Related

How do I use selectors to get different variable for ifs?

I'm working on a tool for my job to auto generate task comments to streamline agent workflow. I'm trying to use a selector to differentiate between ticket types and generate a comment string accordingly.
The problem I'm running into is I can't seem to get the page to tell the the selector has changed, and it will only give the if condition and ignore the else.
I'm certain I'm missing something simple but can't seem to figure it out.
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth() + 1) + '-' + today.getDate() + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date + ' ' + time;
setInterval(1000);
if (tick = 1) {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "# attempt, contacted CX #";
}
}
btn1.addEventListener('click', fun1);
</script>
</html>
A few issues to address:
your comparison needs a double equal - ==
tick itself is just an html element, you can't compare it to a number, you need to get the currently selected index
you use id=ticket twice, so when you get the html element by that ID, it grabs the first one, which is a label.
I believe this code should fix your issues
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket-label"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date+' '+time;
setInterval(1000);
if (tick.selectedIndex == 0){
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"# attempt, contacted CX #";
}
}
btn1.addEventListener('click',fun1);
</script>
</html>
Your value for tick would be a string and you are checking it as integer. Try by changing it to, if (tick == "1").
Label attribute id is same as of select attribute. Try by changing the label id. All HTML attributes must have unique id / name.
In Plain JavaScript, you get the selected option value as follow
var e = document.getElementById("tick");
var value = e.options[e.selectedIndex].value;
Hope this helps! :)

Distance Calculator HTML

Good Day ! Help is greatly appreciated !
function ShowDistance() {
var x1 = parsefloat(document.getElementById('xOne').value);
var x2 = parsefloat(document.getElementById('xTwo').value);
var y1 = parsefloat(document.getElementById('yOne').value);
var y2 = parsefloat(document.getElementById('yTwo').value);
var distance = Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2));
return distance;
if (!isNaN(result)) {
document.getElementById('outPut').innerHTML = 'The distance bewtween (' + x1 + ',' + y1 + ') and (' + x2 + ',' + y2 + ') is ' + distance + ;
}
}
<!doctype html>
<html>
<head>
<title> Distance Calculator </title>
</head>
<body>
<h2>Distance Calculator</h2>
Coordinate 1 (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br> Coordinate 2 (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<button onclick="ShowDistance()">Calculate</button>
</body>
</html>
can't print the result. That is the only problem . I can't print the result.
Please help me. your reply will be great much appreciated
There are a lot of mistakes in your code;
1- First of all, not parsefloat it should be parseFloat;
2- The second one, you return from the ShowDistance without showing the result;
3- Third one, in the if clause should be if(!isNaN(distance)) and not if(!isNaN(result));
4- You did forget to create the Html tag with output id where you wanted to print the result.
all of the code;
<!doctype html>
<html>
<head>
<title> Distance Calculator </title>
</head>
<body>
<h2>Distance Calculator</h2>
Coordinate 1 (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br>
Coordinate 2 (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<button onclick="ShowDistance()">Calculate</button>
<div id="outPut">
</div>
<script>
function ShowDistance()
{
var x1=parseFloat(document.getElementById('xOne').value);
var x2=parseFloat(document.getElementById('xTwo').value);
var y1=parseFloat(document.getElementById('yOne').value);
var y2=parseFloat(document.getElementById('yTwo').value);
var distance =Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
if (!isNaN(distance))
{
document.getElementById('outPut').innerHTML='The distance bewtween (' + x1 + ',' + y1 + ') and (' + x2 + ',' + y2 + ') is '+ distance;
}
return distance;
}
</script>
</body>
</html>
return distance;
Will cause any subsequent code not to be ran, as the return keyword will stop the execution of code, so:
if (!isNaN(distance))
{
document.getElementById('outPut').innerHTML='The distance bewtween (' + x1 + ',' + y1 + ') and (' + x2 + ',' + y2 + ') is '+ distance;
}
Will never run.
Place the code above the return, or remove the return as the value it returns isn't used. You should see a new result.

How to create program to Calculate Resistors in Series using javascript?

i'm newbie in here. i want to create program to calculate resistors in series using HTML & javascript.
I have tried to make it with code below. there are 2 functions.
first, to create input fields automatically based on how many resistors you wants to input.
image 1.( i have created this function ).
and the second function is sum the total values of the input fields that have been created.
image 2. ( i'm not yet create this function )
how to create this ? could you complate the second function ? or any have other alternative ?
JAVASCRIPT :
< script >
function display() {
var y = document.getElementById("form1").angka1.value;
var x;
for (x = 1; x <= y; x++) {
var a = document.getElementById("container");
var newInput = document.createElement('div');
newInput.innerHTML = 'R ' + x + ': <input type="text" id="r_' + x + '" name="r_' + x + '"/>';
a.appendChild(newInput);
}
}
function count() {
//this function not yet created
}
</script>
HTML:
<form id="form1" name="form1" onsubmit="return false">
<label for="number">Input Qty of Resistors </label>
<input type="number" name="angka1">
<input type="submit" value="Display Input" onclick="display()">
<div id="container"></div>
<input type="submit" value="Count" onclick="count()">
</form>
Here is the working demo of what you want to achieve. Click Here
Note that here in demo I have use JQuery so please include jquery file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="number">Input Qty of Resistors </label>
<input type="number" id="angka1" />
<input type="button" value="Display Input" onclick="display()" />
<div id="container"></div>
<input type="button" value="Count" onclick="count()" />
<label id="totalCount"></label>
function display() {
document.getElementById("container").innerHTML = "";
var y = document.getElementById("angka1").value;
var x;
for (x = 1; x <= y; x++) {
var a = document.getElementById("container");
var newInput = document.createElement('div');
newInput.innerHTML = 'R ' + x + ': <input type="number" id="r_' + x + '" name="r_' + x + '" />';
a.appendChild(newInput);
}
}
function count() {
console.log("Count function is called.");
var total = 0;
$("#container input").each(function () {
total += Number($(this).val().trim());
console.log(total);
});
document.getElementById("totalCount").innerHTML = total;
}
Hope that will work for you.

What's wrong with my HTML and javascript code?

I want to implement a simple measurement convergence program but the convert button doesn't really work and it's not even changing the value of the answer box. What should I do now?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Measurement Conversion</title>
</head>
<body>
<h1 align="center">
Measurement Conversion
</h1>
<div align="center"><center><table border="0">
<tr>
<input type="text" name="what" size="15">
</tr>
<tr>
<td align="center">From:<br>
<select name="unit" size="9" onChange="convert()">
<option name="meter">meter</option>
<option name="mile">mile</option>
<option name="yard">yard</option>
</select></td>
</tr>
<tr>
<input type="button" onclick="convert()">Convert it now!</button></td>
</tr>
<tr>
<input type="text" name="answer" title="answer" size="70" value="None"></td>
</tr>
</table>
</center></div>
<script>
function convert() {
// var FromVal, ToVal, FromName, ToName, v1;
v1 = document.getElementByName("what").value;
document.getElementByName("answer").value = v1;
var unit = document.getElementByName("unit").name;
if (unit == "yard") {
var meter = "meter= " + 0.9144*document.getElementByName("what").value;
var mile = "mile = " + 0.000568181818*document.getElementByName("what").value;
document.getElementById("answer").value = meter + mile;
}
if (unit == "meter") {
var yard = "yard = " + 1.0936133*document.getElementByName("what").value;
var mile = "mile = " + 0.000621371192*document.getElementByName("what").value;
// var meter = "m = " + 0.9144*document.getElementByName("what").value
document.getElementById("answer").value = yard + mile;
}
if (unit == "mile") {
var meter = "meter = " + 1609.344*document.getElementByName("what").value
var yard = "yard = " + 1760*document.getElementByName("what").value
document.getElementById("answer").value = meter + yard;
}
}
</script>
</body>
</html>
It seems there is something wrong with my convert() function.
How about using the most basic troubleshooting methods first and then coming here and asking specific questions to help get you through the problem.
Add an alert("button Clicked");
to the first line of your function and see if you get the alert. If you do, move the alert to after your variable statements and change it to
alert("what = " + what + ", "answer = " + answer + ", unit = " + unit);
and make sure you are getting what you expect for your variable assignments. Continue like this and when you get to a specific problem that your can't seem to remedy yourself, come back.
there's no getElementByName.
add attribute id on your input then use getElementById instead.

Simple Javascript Calculator

I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:
<head>
<script type="text/javascript">
function adder(a,b) {
var a = document.getElementById('firstNum').value;
var b = document.getElementById('secondNum').value;
var numbers = new Array(a,b);
var sum = 0;
for (i=0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
//this part i need help with
document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
</script>
</head>
<body>
<form id="additionForm">
A + B = C : <input type="text" id="firstNum" placeholder="A">
+ <input type="text" id="secondNum" placeholder="B">
<input type="button" id="addBtn" value="Add" onClick="adder();">
= <input type="text" id="answer" placeholder="C">
</form>
</body>
My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.
function adder() {
var a = parseInt( document.getElementById('firstNum').value, 10);
var b = parseInt( document.getElementById('secondNum').value, 10);
var sum = a + b;
//this part i need help with
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
If you want to modify an input field in javascript, you can simply set the value attribute:
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;

Categories