This question already has answers here:
how do I set input from user to the value of an input?
(2 answers)
Closed 6 years ago.
I am not exactly new at coding,
But I am definitely an amateur (especially in Javascript), and I have just started a new project for personal purpose.
I can not seem to get my Javascript to print out my answer, and I do not want to move on with the project until I figure it out, because it is going to have more complicated calculations as I work on it.
My code is as below:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p>Enter Your Macros</p>
<p>Fats</p>
<input type="number" name="fats" id="fatInput"/><br>
<button onclick="myFunction()">Calculate</button><br>
<p id="todaysFat"></p>
<script>
function myFunction() {
var f = document.getElementById("fatInput").innerHTML;
document.getElementById("todaysFat").innerHTML = f;
}
</script>
</body>
</html>
Thank you for all of the help
try;
function myFunction() {
var f = document.getElementById("fatInput").value;
document.getElementById("todaysFat").innerHTML = f;
}
I don't think it's the innerHTML your want but the value of the INPUT.
So that's .value not innerHTML.
eg..
var f = document.getElementById("fatInput").value;
Change the innerhtml to value in the first line.
See the below code:
function myFunction() {
var f = document.getElementById("fatInput").value;
document.getElementById("todaysFat").innerHTML = f;
}
<p>Enter Your Macros</p>
<p>Fats</p>
<input type="number" name="fats" id="fatInput" />
<br>
<button onclick="myFunction()">Calculate</button>
<br>
<p id="todaysFat"></p>
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was playing a bit more with html to add to my website, and following this question Dissappear content with html, I now have a phone number box and my javascript code tells me how many characters are in the inputs box, but also includes the spaces. Is there anyway for my javascript to calculate how many characters there are excluding the the spaces?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<input id="id"></input>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var a = document.getElementById("id").value
var str = a
var n = str.length;
if(n==10) {
document.getElementById("demo").innerHTML = "Equal to 10"
}
else {
document.getElementById("demo").innerHTML = "Not equal to 10"
}
}
</script>
</body>
</html>
There's quite a bit that you can and should do to your code (both the HTML and the JavaScript). Some of it will make it more optimized and some of it has to do with the fact that you are using outdated techniques that should be replaced with the modern, standard approach.
See comments inline for details:
<!DOCTYPE html>
<html>
<!-- An HTML document must have a <head> section that
contains a non-empty <title> element. -->
<head>
<title>My Fun Page</title>
</head>
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<input id="id"> <!-- input elements don't have a closing tag -->
<!-- Don't use HTML event attributes to bind JavaScript callbacks.
Do your event binding in JavaScript -->
<button>Try it</button>
<p id="demo"></p>
<script>
// This is the modern way to bind events:
document.querySelector("button").addEventListener("click", myFunction);
// Just get your element references once, not each time the function runs
const demo = document.getElementById("demo");
const input = document.getElementById("id");
function myFunction() {
// Variables are fine, but they don't help you when you
// are only going to use their value once. In that case
// just refer to what you need:
if(input.value.length == 10) {
// Don't use .innerHTML if you can help it as it has security
// and performance implications. Since you aren't working with
// any HTML anyway here, use .textContent
demo.textContent = "Equal to 10"
} else {
demo.textContent = "Not equal to 10"
}
}
</script>
</body>
</html>
No where in your code do you define "Hello World". Remove the "magic number" 10 (which should be 11, unless spaces and punctuation do not count) and replace it with the desired word length.
Also, use triple-equals (===) for value and type comparison.
const
targetWord = "Hello World",
targetLength = targetWord.length;
function myFunction() {
const str = document.getElementById("id").value;
document.getElementById("demo").textContent = str.length === targetLength
? `Equal to ${targetLength}`
: `Not equal to ${targetLength}`;
}
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<input id="id" value="Hello World" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
This is how I would do it.
The ternary expression is maybe not easy to understand for beginners, but I like them.
<script>
function myFunction() {
const str = document.getElementById("id").value
const message = str.length === 10 ? "Equal to 10" : "Not equal to 10"
document.getElementById("demo").innerHTML = message
}
</script>
I am more the hardware guy and my programming skills really suck. I am trying to create things mostly by trial and error and the help of google. I am helping out some GFX-/Ad-Designers, who basically create stuff, place it on a website and have to run those websites thru severals browsers. I am trying to make this less manually handed.
This is run in a HTA. As I said, I am not a programming guy and this was something I could easly work with =/ probably some other language could do this by ease...but as said...
tl;dr
How do I get the value of id="text1" to be added at the end of the URL
shell.run("Firefox https://www.example.com=(text1.value)"); doesnt work.
I does work if I manually change the URL, but than I would not have a handy input-field and changing the URLs by hand...I guess the ad-creating ppl will mess up things.
So, thats what I have done so far...but I can't fix it.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Sub-Site Automation</title>
<hta:application applicationname="Run test on browsers" scroll="yes" singleinstance="yes">
<script type="text/javascript">
function openURL()
{
var input = document.getElementById("text1");
/* console.log(input); // Log
*/
var inputValue = input.value;
/* console.log(inputValue); // Log2
*/
var shell = new ActiveXObject("WScript.Shell");
shell.run("Firefox https://www.example.com=(text1.value)");
shell.run("Chrome https://www.example.com=(text1.value)");
shell.run("file:///C:\Users\*\AppData\Local\Vivaldi\Application\vivaldi.exe https://www.example.com=(text1.value)");
}
</script>
</head>
<body>
<input type="text" id="text1" Name="text1" value="Place ID of subwebsite here"><br>
<input type="submit" Value="Open in all Webbrowsers" onclick="openURL()">
</body>
</html>
Please help!
As I mentioned in the comments, the answer is in your code itself.
See the lines:
// This line gets the element you want
var input = document.getElementById("text1");
// This line gets it's value. You need this value
var inputValue = input.value;
The variable inputValue is what you need to replace there instead of using text1.value.
So your function would be as follows:
function openURL() {
var input = document.getElementById("text1");
var inputValue = input.value;
var shell = new ActiveXObject("WScript.Shell");
shell.run("Firefox https://www.example.com=("+inputValue+")");
shell.run("Chrome https://www.example.com=("+inputValue+")");
shell.run("file:///C:\Users\*\AppData\Local\Vivaldi\Application\vivaldi.exe https://www.example.com=("+inputValue+")");
}
the problem ist that you have no reference to the elements with id text1 so you can not access its value. A second problem is that you try to access a variable inside of a string literal which could be solved in es5 with string concatenation or in newer ecmascript versions with template literals.
Depending on the input value you should also use encodeURIComponent so that the resulting URL is valid.
One version that would work is the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Sub-Site Automation</title>
<hta:application applicationname="Run test on browsers" scroll="yes" singleinstance="yes">
</head>
<body>
<input type="text" id="text1" Name="text1" value="Place ID of subwebsite here"><br>
<input type="submit" Value="Open in all Webbrowsers" onclick="openURL()">
<script type="text/javascript">
function openURL()
{
var text1 = document.getElementById("text1");
var shell = new ActiveXObject("WScript.Shell");
shell.run("Firefox https://www.example.com=" + text1.value);
shell.run("Chrome https://www.example.com=" + text1.value);
shell.run("file:///C:\Users\*\AppData\Local\Vivaldi\Application\vivaldi.exe https://www.example.com=" + text1.value);
}
</script>
</body>
</html>
I am learning some more JavaScript and am having trouble getting a temperature conversion exercise to run.
The below is what I've written so far with the code commented out being a formula from an earlier exercise I did from my instruction book.
Here's the code:
<!--
Challenge:
Write a function to take a temperature in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Hour 2.
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
document.write ("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write ("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
</body>
</html>
-->
<html>
<head>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
</script>
</head>
<body>
<script>
function conversion(a, b) {
var a = 10;
var b = hTemp;
alert (conversion);
}
</script>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Right now when I run the code is displays all the code of the conversion function but doesn't actually convert!
I have been going through this for hours and I feel like the right answer isn't too far away. My question in a nutshell: What do I need to correct to get this to run properly?
Help would be appreciated as I am keen to keep coding but have hit a brick wall here.
You have written alert(conversion), which will basically display the function code, since conversion is a reference to the function.
One other thing, your conversion function takes two variables a and b which is unnecessary as you are not passing any parameters while calling it.
Here is what you can do:
<html>
<head>
<script>
function conversion() {
let cTemp =40; // temperature in Celsius
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
</script>
</head>
<body>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Since you are learning, you should start using best practices. Avoid var for variable declaration and use let instead, as it is block scoped. Instead of using alert you can also use console.log to print values in developer console. I would advise you to search for some tutorials on Google Chrome Developer Tools.
There are several problems with your solution:
You are passing a function to the alert and not the result of the function.
In Javascript you can pass around functions as variables. So if you do alert(conversion), you tell the browser to show the actual function code to the user.
To execute the function, you put parantheses after the function name:
alert(conversion());
You are declaring argument for your function but not using them
Your function is
function conversion(a, b) { …
But you call the function without arguments conversion(), you could call it with arguments like this:
<input type="button" value="Click for Conversion" onclick="conversion(40,10) " />
You are overwriting your arguments without using them
But you will see that nothing changes by adding these numbers, it is because you overwrite them in your function anyway a = 10; b = hTemp. Also if you want to convert a temperature you only should have one input variable. So let us rewrite your function:
function conversion(cTemp) {
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
So now then function accepts an argument called cTemp and then puts out the conversion. You can now call the function with different arguments like this:
<input type="button" value="Click to convert 40 C" onclick="conversion(40) " />
<input type="button" value="Click to convert 50 C" onclick="conversion(50) " />
Or even better, you can do a prompt:
function promptForConversion() {
let cTemp = prompt("Temperature in Celsius");
conversion(cTemp);
}
<input type="button" value="Click to convert number" onclick="promptForConversion(50) " />
These are very basic principles, I highly recommend to do some more tutorials, that also teach you how to organize your code in reusable functions. Good luck!
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am trying to change the text displayed by a div from 'hello' to 'hey' on click using innerHTML. I know my function is executed and the innerHTML is changed because I get an alert on click displaying 'hey', but on my webpage and in inspector the 'text' element's contents remain as 'hello'.
What is going on here?
code:
<html>
<head>
<script type="text/javascript">
function changehtml() {
var text = document.getElementsByClassName('text');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
</script>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
Get elements by class returns an array of elements if you just want to change the one div give it and id and getElementById.
If you want to change multiple divs with that class the second snippet loops through the divs with that class and changes all of their texts.
function changehtml() {
var text = document.getElementById('x');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
<html>
<head>
</head>
<body>
<div id="x" class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
function changehtml() {
var text = document.getElementsByClassName('text');
for (let i = 0; i < text.length; i++) {
text[i].innerHTML = 'hey';
}
}
<html>
<head>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
document.getElementsByClassName('text') gives you collection of nodes. So, you;ll have to loop through them to get each node. Or for this example you can use
document.getElementsByClassName('text')[0];
Or
document.querySelector('.text')
This will give you the first node with class name of text.
And make it your habit to check your console for errors, you'll probably be getting one
This question already has answers here:
De-obfuscate Javascript code to make it readable again [duplicate]
(5 answers)
Closed 7 years ago.
I try to work with javascript from Chrome extension, and have some problems.
Big parts of code including in encode array
var _0x6790 = ["\x44\x4F\x4D\x53\x75\x62\x74\x72\x65\x65\x4D\x6F\x64\x69\x66\x69\x65\x64", "\x67\x65\x74", "\x3A\x76\x69\x73\x69\x62\x6C\x65", "\x69\x73", "\x24\x61\x70\x70\x6C\x79\x46\x6F\x72\x4C\x6F\x6F\x74\x42\x75\x74\x74\x6F\x6E", "\x65\x6E\x61\x62\x6C\x65\x64", "\x61\x75\x74\x6F\x63\x6C\x69\x63\x6B\x69\x6E\x67", "\x73\x65\x74\x74\x69\x6E\x67\x73", "\x6D\x61\x67\x69\x63", "\x63\x6C\x69\x63\x6B", "\x5F\x62\x69\x64\x49\x6E\x74\x65\x72\x6E\x61\x6C\x44\x65\x6C\x61\x79", "\x61\x75\x74\x6F\x62\x69\x64\x64\x69\x6E\x67", "\x23\x67\x6F\x6C\x64\x73\x6C\x69\x64\x65\x72", "\x73\x65\x74\x42\x69\x64", "\x6F\x6E", "\x5F\x69\x6E\x73\x74\x61\x6E\x63\x65"];
and is used like this:
$(document)[_0x6790[14]](_0x6790[0], function() {
How can I decode the values in the array?
this is a worked demo that can help you:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script>
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
document.getElementById('result').innerHTML=str;
}
</script>
</head>
<body>
<h1><u>Hex Decoder</u></h1><br>
<h3><u>Hex code</u></h3>
<textarea id="hexcode" rows="4" cols="50"></textarea><br>
<button type="button" onclick="hex2a(document.getElementById('hexcode').value)">decode</button><br>
<h3><u>Result</u></h3>
<textarea id="result" rows="4" cols="50"></textarea>
</body>
</html>