Display the result of a function as variable in a browser using document.getElementbyId.innerHTML in JavaScript - javascript

I am a newbie to JavaScript < 1 Week old
I wrote a very short HTML/JavaScript and got it to display on console.
Basically, I want to display the result of a function used as a variable inside the <p> tag of the HTML.
I got the script to display in the console.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
</script>
<script>
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
</script>
<p id="Kilograms"><!--I want the result here--></p>
</body>
</html>
How do I get the result of the function as a variable i.e var kilo (pounds)... to display in the p tag with id Kilograms?

Script shold be after BODY code, or you should add document ready event listener. So, try this solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="Kilograms"><!--I want the result here--></p>
</body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
document.getElementById("Kilograms").innerHTML = kilog(440);
</script>
</html>
Example in JSBin: https://jsbin.com/pacovasuve/edit?html,output

You can try this in your js code.
document.getElementById("Kilograms").innerHTML="write whatever you want here";

Try this
var p = document.getElementById('Kilograms');
p.innerHtml = 'any text';
// OR
p.innerHtml = kilog(440);

Related

how to raise the prompt event and post to jsp?

I want to post a prompt value to a jsp.. but I can't run the jsp page... Are there any mistakes in my code?
I want to make a prompt for a user to insert a value, then straight away submit it to a JSP to run the calculation... but it can't run...
html
<html>
<head>
<title>Lab Exercise 1 for Lab 3</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script>
var celcius = prompt("Pleae enter current temperature in celcius.");
if(celcius!==null){
$.post("calculation.jsp",
{temp:celcius},
);
}
</script>
</body>
Jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Temperature Converter</title>
</head>
<body>
<h1>Celsius to Fahrenheit:</h1>
<%
String celsius = request.getParameter("temp");
double thecelsius = Double.parseDouble(celsius);
double fahrenheit = ((9/5)*thecelsius + 32);
%>
The temperature in Fahrenheit for <%=celsius%> celsius is <%=fahrenheit%>F.
</body>
You are using ajax so you need to return response back and then you can show result inside callback of ajax i.e :
var celcius = prompt("Pleae enter current temperature in celcius.");
if (celcius !== null) {
$.post("calculation.jsp", {
temp: celcius
}, function(data) {
//here data will come back ..
$("#result").text(data) //you can set some data to divs..
});
}
and your jsp will look like below :
<%
//other codes
//below will send back to ajax ...
out.println("The temperature in Fahrenheit for "+celsius+"celsius is "+fahrenheit+"F");
%>
Other way :
You can simply redirect to that page using window.location.href = "calculation.jsp?temp="+celcius . But , this will be GET request not POST .

Javascript - setTimeout

I am learning Javascript right now. I have a small issue that I can't figure out how to solve it. I would like to clear content of my html page after my function displayed "Hi hi" in web page.
<html>
<body onload="alertFunc()">
<script>
function alertFunc() {
var statement = "Hi hi"
for (let i = 0; i < statement.length; i++) {
let c = statement.charAt(i);
setTimeout(function(){
document.write(c);
},i * 1000);
}
}
</script>
</body>
</html>
try this to clear content of your site after 1 second
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning </title>
</head>
<body>
<script>
document.write('hi hi');
function alertFunc() {
setTimeout(function(){
document.write(' ');
}, 1000);
}
alertFunc();
</script>
</body>
</html>
if you want to change content with time again and again then you have to use setInterval

document.creatElement can't show utf8 chars

I create label elem with document.crteateElement and I set text value to elem with .innerHTML but on page browser don't show utf-8 characters correct I see only '?' in black rectangle.
This my hrml charset:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-9">
<META HTTP-EQUIV="Content-language" CONTENT="tr">
I use this function for convert :
GetChar(char) {
return unescape(decodeURIComponent(char))
}
and this is my value
const target= '${this.GetChar('İ')}stikamet'
then here is I set value to label elem
var elem = document.createElement('label)
elem.innerHTML = target
What is the corrent way show this characters on browser ?
Try this instead of your current meta-tags
<meta charset="UTF-8">
EDIT:
The following HTML displays your example-char fine for me:
<html>
<meta charset="UTF-8">
<body>
<label>İ</label>
</body>
</html>

How do I show timer on click of link?

So if you notice I have created a link in the preview below. What I'm looking for is if someone clicks on the link. I want to replace the text for a 60 seconds timer, and once the 60 seconds are finished, the text and link should reappear, and the same process continues.
Can someone help?
Request code again
You can use javascript setInterval and then clearInterval for this.
Your code while using jQuery should look like this: (change the value of timer_output_initial to time in number of seconds you want)
var display_timer_interval;
var timer_output_initial = 5
var timer_output = timer_output_initial;
var initial_text = "";
$("#timer_link").on("click",function(){
var clicked_element = $(this);
initial_text = clicked_element.html();
display_timer_interval = setInterval(function(){
display_time(clicked_element);
}, 1000);
});
function display_time(element){
timer_output = timer_output-1;
if(timer_output === 0) {
clearInterval(display_timer_interval);
timer_output = timer_output_initial;
element.html(initial_text);
}else{
$(element).html(timer_output);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
Request code again
</body>
</html>

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

Categories