Simple temperature converter (javascript, html, try-catch) not working - javascript

I'm a complete beginner with coding and I need to write a simple program with javascript and html for an exam, but I need to stick to my professor' standard (hence the specific way this code looks).
I tried to make a simple temperature converter (celsius to fahrenheit) but I don't understand why nothing happens when I click the "convert" button.
EDIT: for some reason the converter works fine here, but when I open it in a new window it doesn't work at all. Any idea why that might be?
function writeText (node, message) {
var nodeText = document.createTextNode(message);
node.replaceChild(nodeText, node.firstChild);
}
function convertHandler () {
try {
if (nodeTemperature.value =="") {
writeText("the field is empty");
return;
}
var temperature = Number(nodeTemperature.value);
if (isNaN(temperature)) {
writeText(nodeTemperature.value + " is not a number");
return;
}
nodeResult.value = temperature * (9/5) + 32;
} catch ( e ) {
alert("convertHandler" + e);
}
}
var nodeTemperature;
var nodeConvert;
var nodeResult;
var ConvertMessage;
function loadHandler () {
try {
nodeTemperature = document.getElementById("temperature");
nodeConvert = document.getElementById("convert");
nodeResult = document.getElementById("result");
nodeConvertMessage = document.getElementById("convertMessage");
nodeTemperature.value = "";
nodeResult.value = "";
nodeConvert.onclick = convertHandler;
var nodeText = document.createTextNode("");
nodeConvertMessage.appendChild(nodeText);
} catch ( e ) {
alert("loadHandler" + e);
}
}
window.onload = loadHandler;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script scr="p3.js"></script>
<title>Temperature converter</title>
</head>
<body>
<h1>Convert Celsius in Fahrenheit</h1>
<input type="text"
id="temperature"/> Celsius
<br>
<input type ="button"
id="convert"
value="Convert"/>
<span id="convertMessage"></span>
<br>
<input type="text"
id="result"
readonly="readonly"/>Fahrenheit
</body>
</html>
If someone could help me that would save my (academic) life, thank you.

Related

setAttribute, onclick, eventListener won't work

So i have this code in javascript that replaces the text from the html, depending on the language you click on ( romanian or english, default is romanian). I tried all of the 3 ways i know for the click action, but none of them work. Can you please help me?
EDIT:
The first couple of instructions don't work at all ( nothing happens, not even when clicking on them). Then, the last bouth couples execute at the onload (but don't work after, when click on them). I see that using addEventListener with the listener function doesn't work with other parameters than just the event itself, but I'm still confused about the other ways
<html lang = "en">
<head>
<title>
Website
</title>
<meta charset = "UTF-8">
</head>
<body>
<a id='english' >English</a>
<a id='romanian'>Romanian</a>
<p id="paragraph">
Bine ai venit pe site-ul meu!
</p>
<script>
localStorage.setItem("languageStored" , "romanian");
var language = {
eng: {
welcome: "Welcome to my website!"
},
ro: {
welcome: "Bine ai venit pe site-ul meu!"
}
};
window.onload = function()
{
let optEngl = document.getElementById('english');
let optRo = document.getElementById('romanian');
// optRo.setAttribute('click' ,'languageChange(this , optRo)' );
// optEngl.setAttribute('click','languageChange(this , optEngl)');
// optEngl.onclick = languageChange(this , optEngl);
// optRo.onclick = languageChange(this , optRo);
// optEngl.addEventListener("click" , languageChange(this , optEngl));
// optRo.addEventListener("click" , languageChange(this , optRo));
}
function languageChange(e , obj)
{
let languageStored = localStorage.getItem("languageStored");
if(languageStored != obj.id)
{
console.log(obj.id);
languageStored = obj.id;
localStorage.setItem("languageStored" , languageStored);
if(languageStored == "english")
document.getElementById('paragraph').textContent = language.eng.welcome;
else
document.getElementById('paragraph').textContent = language.ro.welcome;
}
}
</script>
</body>
</html> ```
.addEventListener takes a callback as the second parameter, so you don't need the () when you're adding your function.
Also, you can use this inside the callback function to refer to the Element that the Event triggered from - this just cleans up the function code a little bit - You don't need to includig any parameters to your languageChange function
LocalStorage doesn't work with Snippets on this site, so I wrote a quick Codepen to show the changes
localStorage.setItem("languageStored", "romanian");
var language = {
eng: {welcome: "Welcome to my website!"},
ro: {welcome: "Bine ai venit pe site-ul meu!"}
};
window.onload = function() {
let optEngl = document.getElementById('english');
let optRo = document.getElementById('romanian');
optEngl.addEventListener('click', languageChange);
optRo.addEventListener('click', languageChange);
}
function languageChange() {
// Get the Language stored
let languageStored = localStorage.getItem("languageStored");
// You can use `this` rather than `obj` to refer to the Clicked Element
if (languageStored != this.id) {
languageStored = this.id;
localStorage.setItem("languageStored", languageStored);
if (languageStored == "english")
document.getElementById('paragraph').textContent = language.eng.welcome;
else
document.getElementById('paragraph').textContent = language.ro.welcome;
}
}
}
I made couple of changes to your code.First, I think you can directly call functions from a tag and no need of window.onload. One issue I found with your code was when you were sending optEngl you were just sending as optEngl without any quotes which made js think it wasn't string. Then, I modified your string comparison within languageChange function using localeCompare rather than ==. Then, it worked fine. I hope this helps.
<html lang="en">
<head>
<title>
Website
</title>
<meta charset="UTF-8">
</head>
<body>
<a id='english' onClick="languageChange(this , 'optEngl');">English</a>
<a id='romanian' onClick="languageChange(this , 'optRo');">Romanian</a>
<p id="paragraph">
Bine ai venit pe site-ul meu!
</p>
<script type="text/javascript">
localStorage.setItem("languageStored", "romanian");
var language = {
eng: {
welcome: "Welcome to my website!"
},
ro: {
welcome: "Bine ai venit pe site-ul meu!"
}
};
function languageChange(e, obj) {
let languageStored = localStorage.getItem("languageStored");
if (languageStored != obj) {
localStorage.setItem("languageStored", obj);
if (languageStored.localeCompare("optEngl")) {
document.getElementById('paragraph').textContent = language.eng.welcome;
} else {
document.getElementById('paragraph').textContent = language.ro.welcome;
}
}
}
</script>
</body>
</html>
If you want to see results, check out jsfiddle snippet
By using javascript:
<html lang="en">
<head>
<title>
Website
</title>
<meta charset="UTF-8">
</head>
<body>
<a id='english'>English</a>
<a id='romanian'>Romanian</a>
<p id="paragraph">
Bine ai venit pe site-ul meu!
</p>
<script type="text/javascript">
localStorage.setItem("languageStored", "romanian");
var language = {
eng: {
welcome: "Welcome to my website!"
},
ro: {
welcome: "Bine ai venit pe site-ul meu!"
}
};
window.onload = function() {
let optEngl = document.getElementById('english');
let optRo = document.getElementById('romanian');
optEngl.onclick = function() {
languageChange(this, "optEngl");
}
optRo.onclick = function() {
languageChange(this, "optRo");
}
}
function languageChange(e, obj) {
let languageStored = localStorage.getItem("languageStored");
if (languageStored != obj) {
localStorage.setItem("languageStored", obj);
if (languageStored.localeCompare("optEngl")) {
document.getElementById('paragraph').textContent = language.eng.welcome;
} else {
document.getElementById('paragraph').textContent = language.ro.welcome;
}
}
}
</script>
</body>
</html>

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

Unknown symbols displayed in czech words in javascript application

I have an unknown symbols displayed in my javascript application for try catch construction using czech language even when I use coding windows-1250. These symbols is displayed like question marks in diamond.
html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250"/>
<title>Konstrukce Try/Catch</title>
<script type="text/javascript" src="number.js"></script>
</head>
<body>
<form name="formular" id="formular" action="#">
<div id="cisloDiv">Zadejte číslo v rozsahu 1 až 100: <input id="cislo" name="cislo"> <span id="informace"> </span></div>
<div><input id="odeslatFormular" type="submit"></div>
</form>
<script type="text/javascript">
function inicializuj() {
document.forms[0].onsubmit = function() { return zkontrolujFormular(this) };
}
window.onload = inicializuj;
</script>
</body>
</html>
javascript
function zkontrolujFormular() {
try {
var cislo = document.forms[0]["cislo"];
if (isNaN(cislo.value)) {
var chyba = new Array("Nejedná se o číslo",cislo);
throw chyba;
}
else if (cislo.value > 100) {
var chyba = new Array("Zadané číslo je větší jak 100",cislo);
throw chyba;
}
else if (cislo.value < 1) {
var chyba = new Array("Zadané číslo je menší jak 1",cislo);
throw chyba;
}
return true;
}
catch(objektVyjimky) {
var informace = document.getElementById("informace");
var textChyby = document.createTextNode(objektVyjimky[0]);
var novySpan = document.createElement("span");
novySpan.appendChild(textChyby);
novySpan.style.color = "#FF0000";
novySpan.style.fontWeight = "bold";
novySpan.setAttribute("id","informace");
var rodic = informace.parentNode;
rodic.replaceChild(novySpan,informace);
objektVyjimky[1].style.background = "#FF0000";
return false;
}
}
Have you tried using UTF-8 encoding?
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
or shorter:
<meta charset="utf-8" />
Nowadays using encoding other that UTF-8 is rather rare. You may need it in special circumstances, but whenever you can try to use UTF.
Now I have the solution, something was bad in my code because in solution (it is from learning material) it works.

Chrome Browser Issue for Button

I have an issue with a Button. It is appearing in IE and Firefox, but not appearing in Chrome.
The code for the button is using Rally API and it’s generated while loading the page.
I have tried Googling the answer, but I couldn't find anything.
Heres my code:
function onClick(b, args) {
if(OneButtonClickFlag == true) {
OneButtonClickFlag = false;
var buttonValue = args.value;
var userName = "__USER_NAME__";
TimeSheetReport(); // calling the “timesheet report “
}
}
function onLoad() {
var config = {
text: "Generate",
value: "myValue"
};
var button = new rally.sdk.ui.basic.Button(config);
button.display("buttonDiv", onClick); // call the “onclick” function
}
rally.addOnLoad(onLoad);
This App below seems to work with your code in it up until the point where it encounters your OneButtonClick flag. I tested it in Chrome. Does this work for you?
<head>
<title>Button Example</title>
<meta name="Name" content="Component Example: Button"
/>
<meta name="Version" content="2010.4" />
<meta name="Vendor" content="Rally Software" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.26/sdk.js"></script>
<script type="text/javascript">
function onClick(b, args) {
console.log("works until this undefined variable");
if (OneButtonClickFlag == true) {
OneButtonClickFlag = false;
var buttonValue = args.value;
var userName = "__USER_NAME__";
TimeSheetReport(); // calling the “timesheet report “
}
}
function onLoad() {
var config = {
text: "Generate",
value: "myValue"
};
var button = new rally.sdk.ui.basic.Button(config);
button.display("buttonDiv", onClick); // call the “onclick” function
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<div id="buttonDiv"></div>
</body>

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources